﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Media;
using System.Windows.Forms;
using SoftwareConsulting.BI11.Controls;
using SoftwareConsulting.BI11.Controls.Ribbon;
using SoftwareConsulting.BI11.Studio.Core.DBProviders;
using SoftwareConsulting.BI11.Studio.Core.Project;
using SoftwareConsulting.BI11.Studio.Core.Project.Metadata;
using SoftwareConsulting.BI11.Studio.Core.Project.Metadata.Extensions;
using SoftwareConsulting.BI11.Studio.Core.Project.SituationsHierarchy;
using SoftwareConsulting.BI11.Studio.Core.Users;
using SoftwareConsulting.BI11.Studio.InternalServices;
using SoftwareConsulting.BI11.Studio.ProcessWait;
using SoftwareConsulting.BI11.Studio.UI.IDE;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.ClassificationProblems;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.Calculations;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.Dimensions;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.Extensions;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.Indicators;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.Models;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.SituationsHierarchy;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.Tables;
using SoftwareConsulting.BI11.Studio.UI.ProjectExplorer.TimeSeries;
using SoftwareConsulting.BI11.Studio.UI.Properties;
using SoftwareConsulting.BI11.Studio.UI.Users;
using SoftwareConsulting.BI11.Studio.UI.Workflow;
using SoftwareConsulting.BI11.Controls.Metadata;
using SoftwareConsulting.Interfaces.BasicEntities;

namespace SoftwareConsulting.BI11.Studio.UI.ProjectExplorer
{
    /// <summary>
    /// Класс формы обозревателя проекта
    /// </summary>
    public partial class ProjectExplorerForm : RibbonRestorableForm
    {
        private ProjectDescriptor _projectLink; //для связи с проектом
        private ViewType _view; //вид отображения объектов
        private DataGridView _grdFields; //грид полей пользовательских таблиц/измерений куба
        private ToolStrip _toolFields; //тулбар грида полей пользовательских таблиц/измерений куба/измерения расчета
        private ToolStrip _modelsTools; //тулбар моделей расчета
        private DateTimePicker _fromDateBox; //бокс выбора начальной даты
        private DateTimePicker _tillDateBox; //бокс выбора конечной даты
        private DateTimePicker _identfromBox; //бокс выбора начальной даты идентификации
        private DateTimePicker _identtillBox; //бокс выбора конечной даты идентификации
        private DateTimePicker _forefromBox; //бокс выбора начальной даты прогнозирования
        private DateTimePicker _foretillBox; //бокс выбора конечной даты прогнозирования
        private ComboBox _dynBox; //комбик динамики календарного измерения        
        private Panel _situationsBoxPanel; //панель бокса иерархии ситуаций
        private CorrelationsBox _situationsBox; //бокс иерархии ситуаций
        private ToolStrip _situationsAreaTip; //панель подсказки области ситуаций
        private MainForm _MainFormLink; //для связи с главной формой
        private MetadataObjectsVisibleTypes _visibleTypes; //тип отображаемых объектов        
        private bool _programFocusChange; //флаг программного изменения фокуса в списке объектов
        private bool _programKindChange; //флаг программного изменения фокуса в списке видов объектов
        private bool _programTreeBuild; //флаг программного построения дерева
        private Settings _curSettings;//текущие настройки     
        private ProjectSettings _curProjectSettings;//текущие настройки, относящиеся к проекту
        private IDEForm _IDEWindow; //ссылка на форму среды разработки
        private AboutDialog _aboutProgramDialog; //ссылка на диалог "о программе"
        private WorkflowForm _workflowWindow; //ссылка на форму системы документооборота        
        //теперь риббоныprivate PreferencesDialog _preferencesForm; //ссылка на форму оформления        
        private SettingsDialog _settingsForm; //ссылка на форму настроек
        private SystemDBProvider _systemDB; //для связи с БД системы
        private IUsersList _usersList; //список пользователей системы        
        private bool _blockAccessToAppFolder; //флаг отключения возможности проводить любые операции, требующие доступа к системной папке AppData        
        private bool _failedLogon; //флаг провалившейся авторизации            
        private bool _canceledLogon; //flag of canceled authorization;
        private ICollection<RapidAnalysisForm> _rapidAnalysisWindows;//список форм быстрого анализа
        private SoundPlayer _soundsPlayer;//доступ к проигрывателю звуков
        private bool _blockRibbon; //флаг блокировки редактирования состояния пунктов основного меню                                        
        private Timer _saveAbilityTimer;
        private Guid _selectedContainerId; //идентификатор выбранного контейнерного объекта
        private bool _cutOperation; //флаг операции вырезки
        private List<IMetadataObjectDescriptor> _cuttedItemsDescriptors; //описатели вырезанных объектов
        private bool _handheldPropertiesClose; //флаг ручного скрытия панели свойств объекта
        private List<Guid> _beforeSelectedObjectsIds; //список ранее выделенных объектов
        private MetadataObjectsHistory _objectsHistory; //история перемещения по объектам
        private int _historyFocus; //фокус в истории перемещения по объектам
        private HashSet<Guid> _treeExpanded; //флаги раскрытых контейнерных объектов в дереве контейнерных объектов
        private Timer _objectsSelectionTimer; //таймер смены выделения объектов (для убирания миганий)
        private RibbonContextTabs _metadataTabs; //вкладки работы с метаданными        
        private RibbonContextTabs _shortcutsTabs; //вкладки работы со ссылками
        private RibbonContextTabs _actionsetsTabs; //вкладки работы со сводами действий
        private RibbonContextTabs _dataTabs; //вкладки работы с данными
        private RibbonContextTabs _situationsTabs; //вкладки работы с иерархией ситуаций        
        private RepositoryConnector _repoConnector;//соединитель с репозиторием
        private bool _inObjectF2Renaming;//флаг нахождения в состоянии переименования объекта через F2
        private bool _blockObjectsListAutoRefresh;//флаг блокировки автообновления списка объектов при изменении репозитория

        /// <summary>
        /// Возвращает/устанавливает идентификатор выделенного контейнерного объекта
        /// </summary>
        public Guid SelectedContainerId
        {
            get
            {
                if (IsTreeEnabled)
                    return _selectedContainerId;
                return _projectLink.RepositoryLink.RootFolder.Id;
            }
            set
            {
                if (_selectedContainerId != value)
                {
                    _selectedContainerId = value;
                    RefreshTree();
                }
            }
        }

        /// <summary>
        /// Фокусируется на указанном элементе истории перемещения по объектам
        /// </summary>
        /// <param name="histItem"></param>
        /// <returns></returns>
        private bool FocusObject(MetadataObjectsHistoryPoint histItem)
        {
            return FocusObject(histItem.Descriptor, histItem.Kind);            
        }

        /// <summary>
        /// Фокусируется на указанном объекте
        /// </summary>
        /// <param name="metadataObject"></param>
        /// <returns></returns>
        public bool FocusObject(IMetadataObject metadataObject)
        {
            return FocusObject(metadataObject.Descriptor);
        }

        /// <summary>
        /// Фокусируется на указанном объекте
        /// </summary>
        /// <param name="objectDescriptor"></param>
        /// <returns></returns>
        public bool FocusObject(IMetadataObjectDescriptor objectDescriptor)
        {
            return FocusObject(objectDescriptor, MetadataObjectsHistoryPointKind.SimpleMetadataObject);
        }

        /// <summary>
        /// Устанавливает точку истории перемещения по объектам
        /// </summary>
        /// <param name="descriptor"></param>
        /// <param name="pointKind"></param>
        private void PutHistoryPoint(IMetadataObjectDescriptor descriptor, MetadataObjectsHistoryPointKind pointKind)
        {
            if ((_historyFocus < 0) || (_objectsHistory[_historyFocus].Descriptor.Id != descriptor.Id) || (_objectsHistory[_historyFocus].Kind != pointKind))
            {
                //переходим на совершенно новый объект
                if ((_historyFocus != -1) && (_historyFocus < (_objectsHistory.Count - 1)))
                {
                    //мы стоим в середине истории => надо сначала почистить хвост истории
                    _objectsHistory.RemoveRange(_historyFocus + 1, _objectsHistory.Count - _historyFocus - 1);
                }
                _objectsHistory.Add(new MetadataObjectsHistoryPoint(descriptor, pointKind));
                _historyFocus++;
            }
            UpdateAvailableHistoryActions();
        }

        /// <summary>
        /// Фокусируется на указанном объекте
        /// </summary>
        /// <param name="metadataObject"></param>
        private bool FocusObject(IMetadataObject metadataObject, MetadataObjectsHistoryPointKind pointKind)
        {
            return FocusObject(metadataObject.Descriptor, pointKind);
        }

        /// <summary>
        /// Фокусируется на указанном объекте
        /// </summary>
        /// <param name="objectDescriptor"></param>
        private bool FocusObject(IMetadataObjectDescriptor objectDescriptor, MetadataObjectsHistoryPointKind pointKind)
        {
            if (objectDescriptor.Kind == MetadataObjectKind.Folder)
            {
                //контейнерный объект, дерево надо отобразить
                SetTreeEnable(true);                
            }
            if (!VisibleTypes.All)
            {                   
                while (true)
                {
                    if (objectDescriptor.Kind == MetadataObjectKind.Folder)
                    {
                        if (true)
                        {
                            //папка - ее не бывает в отображемых видах
                            break;
                        }
                    }             
                    VisibleTypes = new MetadataObjectsVisibleTypes()
                    {
                        Kind = objectDescriptor.Kind,
                        All = false
                    };
                    break;
                }
            }
            if (pointKind == MetadataObjectsHistoryPointKind.OpenedContainerObject)
            {
                SelectedContainerId = objectDescriptor.Id;
                PutHistoryPoint(objectDescriptor, pointKind);
                ObjectsList.SelectedItems.Clear();
                return true;
            }
            else
            {
                SelectedContainerId = objectDescriptor.ParentId;
                foreach (ListViewItem item in ObjectsList.Items)
                {
                    if ((item.Tag as IMetadataObjectDescriptor).Id == objectDescriptor.Id)
                    {
                        ObjectsList.SelectedItems.Clear();
                        item.Selected = true;
                        item.EnsureVisible();
                        return true;
                    }
                }
            }
            GeneralMethods.ShowUserError(string.Format(Resources.BI_PROJECTEXPLORER_OBJECTNOTFOUND, objectDescriptor.ToString()));
            return false;
        }

        /// <summary>
        /// Возвращает/устанавливает текст подсказки иерархии ситуаций
        /// </summary>        
        public string SituationsAreaTip
        {
            get
            {
                return _situationsAreaTip.Items[0].Text;
            }
            set
            {
                if (_situationsAreaTip == null) //бывает при открытии проекта, если открываем не на просмотре иерархии ситуаций
                    return;
                if (_situationsAreaTip.Items.Count == 0)
                {
                    _situationsAreaTip.Items.Add(value);
                }
                else
                {
                    _situationsAreaTip.Items[0].Text = value;
                }
            }
        }

        /// <summary>
        /// Возвращает список пользователей системы
        /// </summary>
        public IUsersList UsersList
        {
            get
            {
                return _usersList;
            }
        }

        /// <summary>
        /// Возвращает ссылку на провайдера БД системы
        /// </summary>
        public SystemDBProvider SystemDB
        {
            get
            {
                return _systemDB;
            }
        }

        /// <summary>
        /// Возвращает флаг проваленной авторизации
        /// </summary>
        public bool FailedLogOn
        {
            get
            {
                return _failedLogon;
            }
        }

        /// <summary>
        /// Возвращает флаг отмененной авторизации
        /// </summary>
        public bool CanceledLogOn
        {
            get
            {
                return _canceledLogon;
            }
        }

        /// <summary>
        /// Возвращает флаг отключения возможности выполнять любые операции, связанные с доступом к системной папке AppData
        /// </summary>
        public bool BlockAccessToApplicationFolder
        {
            get
            {
                return _blockAccessToAppFolder;
            }
        }

        /// <summary>
        /// Возвращает/устанавливает строку статуса
        /// </summary>
        public string Status
        {
            get
            {
                return StatusText.Text;
            }
            set
            {
                StatusText.Text = value;
                ProjectExplorerStatus.Refresh();
            }
        }

        /// <summary>
        /// Читает список пользователей
        /// </summary>
        private void ReadUsers()
        {
            _systemDB = new SystemDBProvider();
            _usersList = new UsersList(_systemDB);
        }

        /// <summary>
        /// Проверка на возможность закрытия программы
        /// </summary>
        /// <returns>true - закрывать можно; false - нельзя</returns>
        private bool AskBeforeClosing()
        {
            bool toContinue = !_projectLink.Modified;
            if (!toContinue)
            {
                MainFormLink.ShowOrHideSituationsHierarchyForm(true);
                DialogResult d = GeneralMethods.ShowWarning(Resources.BI_PROJECT_DOYOUWANTSAVE, MessageBoxButtons.YesNoCancel);
                switch (d)
                {
                    case DialogResult.Yes:
                        SaveProject();
                        toContinue = true;
                        break;
                    case DialogResult.No:
                        toContinue = true;
                        break;
                }
            }
            if (toContinue)
            {
                _curSettings.ProjectExplorerView = _view;
                _curSettings.ProjectExplorerObjectsGroupsWidth = ObjectsGroupTabControl.Width;
                _curSettings.ProjectExplorerObjectPropertiesWidth = ObjectPropertiesArea.Width;
                List<int> columnsWidth = new List<int>();
                for (int i = 0; i < ObjectsList.Columns.Count; i++)
                {
                    columnsWidth.Add(ObjectsList.Columns[i].Width);
                }
                _curSettings.ProjectExplorerColumnsWidth = columnsWidth;
                _curSettings.ProjectExplorerObjectsGroupsPageIndex = ObjectsGroupTabControl.SelectedTabPageIndex;
                _curSettings.ProjectExplorerObjectsKindsSelectedIndex = ObjectKindsView.SelectedIndices[0];
                _curSettings.ProjectExplorerObjectsTreeEnabled = IsTreeEnabled;
                if (_projectLink.Active)
                {
                    _curSettings.LastProjectPathAndName = _projectLink.GetFullPath();
                }
                _curSettings.SaveMe();
                _curProjectSettings.ProjectExplorerObjectsTreeSelectedContainerId = SelectedContainerId;
                _curProjectSettings.ProjectExplorerTreeExpanded = _treeExpanded;
                _curProjectSettings.SaveMe();

                if (_IDEWindow != null)
                {
                    _IDEWindow.Close();
                }
                if (_workflowWindow != null)
                {
                    _workflowWindow.Close();
                }
                /*теперь риббоныif (_preferencesForm != null)
                {
                    _preferencesForm.Close();
                }*/
                if (_settingsForm != null)
                {
                    _settingsForm.Close();
                }
                MainFormLink.CloseSituationsAreaChilds();
            }
            return toContinue;
        }

        /// <summary>
        /// Обрабатывает тик таймера, чтобы показать возможность сохранения
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void _saveAbilityTimer_Tick(object sender, EventArgs args)
        {
            if ((_projectLink != null) && !_blockRibbon)//в самый момент запуска проги ==null
            {
                bool isModified = _projectLink.Modified;
                bool canSave = isModified && !_blockAccessToAppFolder;
                SaveProjectItem.SetState(!canSave ? SaveProjectItem.State | RibbonItemChangedStates.Disabled : SaveProjectItem.State & ~RibbonItemChangedStates.Disabled);
                FastSaveButton.SetState(!canSave ? FastSaveButton.State | RibbonItemChangedStates.Disabled : FastSaveButton.State & ~RibbonItemChangedStates.Disabled);
            }
        }

        /// <summary>
        /// Реализует автооткрытие последнего файла, с которым работали
        /// </summary>
        public void AutoOpen()
        {
            if (!_projectLink.Active && _curSettings.Autoopen)
            {
                string s = _curSettings.LastProjectPathAndName;
                if (File.Exists(s))
                {
                    OpenProject(s);
                }
            }
        }

        /// <summary>
        /// Вызов диалога создания нового проекта
        /// </summary>
        private void ShowCreateProjectDialog()
        {
            MainFormLink.HierarchyForm.CurrentSituationsArea.IsMultiselectByCtrl = false;
            bool toContinue = !_projectLink.Modified;
            if (!toContinue)
            {
                DialogResult d = GeneralMethods.ShowWarning(Resources.BI_PROJECT_DOYOUWANTSAVE, MessageBoxButtons.YesNoCancel);
                switch (d)
                {
                    case DialogResult.Yes:
                        SaveProject();
                        toContinue = true;
                        break;
                    case DialogResult.No:
                        toContinue = true;
                        break;
                }
            }
            if (toContinue)
            {
                string name = _projectLink.Name;
                string path = _projectLink.Path;
                DialogResult d = DialogResult.OK;
                if (!_blockAccessToAppFolder)
                {
                    ProjectCreatingDialog pars = new ProjectCreatingDialog(name, path);
                    d = pars.ShowDialog();
                    name = pars.ProjectName;
                    path = pars.Path;
                    pars.Close();
                }
                if (d == DialogResult.OK)
                {
                    Processing.BeginWait();
                    CreateProject(name, path);
                    Processing.EndWait();
                }
            }
        }

        /// <summary>
        /// Вызов диалога открытия проекта
        /// </summary>
        private void ShowOpenProjectDialog()
        {
            MainFormLink.HierarchyForm.ReadScrollInfo();
            MainFormLink.HierarchyForm.BlockScrollInfoReading = true;
            bool toContinue = !_projectLink.Modified;
            if (!toContinue)
            {
                DialogResult d = GeneralMethods.ShowWarning(Resources.BI_PROJECT_DOYOUWANTSAVE, MessageBoxButtons.YesNoCancel);
                switch (d)
                {
                    case DialogResult.Yes:
                        SaveProject();
                        toContinue = true;
                        break;
                    case DialogResult.No:
                        toContinue = true;
                        break;
                }
            }
            if (toContinue)
            {
                OpenProjectDialog.InitialDirectory = Application.LocalUserAppDataPath;
                OpenProjectDialog.FileName = string.Empty;
                DialogResult d = OpenProjectDialog.ShowDialog();
                if (d == DialogResult.OK)
                {
                    OpenProject(OpenProjectDialog.FileName);
                }
            }
            MainFormLink.HierarchyForm.SetScrollInfo();
            MainFormLink.HierarchyForm.BlockScrollInfoReading = false;
            MainFormLink.HierarchyForm.CenterSituationsArea();
        }

        /// <summary>
        /// Сохранение текущего проекта как...
        /// </summary>
        private void ShowSaveProjectAsDialog()
        {
            MainFormLink.HierarchyForm.CurrentSituationsArea.IsMultiselectByCtrl = false;
            SaveProjectDialog.InitialDirectory = _projectLink.Path;
            SaveProjectDialog.FileName = _projectLink.Name;
            DialogResult d = SaveProjectDialog.ShowDialog();
            if (d == DialogResult.OK)
            {
                string fname = SaveProjectDialog.FileName;
                _projectLink.SetName(Path.GetFileNameWithoutExtension(fname));
                _projectLink.Path = Path.GetDirectoryName(fname);
                SaveProject();
                UpdateCaptionName();                
                if (_IDEWindow != null)
                {
                    _IDEWindow.UpdateCaptionName();
                }
                if (_workflowWindow != null)
                {
                    _workflowWindow.UpdateCaptionName();
                }
                UpdateCaptionName();
            }
        }

        /// <summary>
        /// Собственно сохранение проекта
        /// </summary>
        public void SaveProject()
        {
            Guid stateId = ProjectDescriptor.SetStateOfPreparationOn(PreparationStates.Serialization);
            Processing.BeginWait();
            try
            {
                MainFormLink.HierarchyForm.CurrentSituationsArea.IsMultiselectByCtrl = false;
                Status = Resources.BI_PROJECT_SAVING;
                SituationsArea curSA = MainFormLink.HierarchyForm.CurrentSituationsArea;
                SituationsHierarchyScale sc = curSA.Scale;
                if (sc != SituationsHierarchyScale.Normal)
                {
                    curSA.SavingScaleSituationBox = null;
                    MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.Normal);
                }
                _projectLink.Save();
                curSA.Save();
                if (sc != SituationsHierarchyScale.Normal)
                {
                    curSA.ScalingFactorForRectangleX = 1 / curSA.ScalingFactorForRectangleX;
                    curSA.ScalingFactorForRectangleY = 1 / curSA.ScalingFactorForRectangleY;
                    curSA.BlockRectangleScaleRecalculating = true;
                    switch (sc)
                    {
                        case SituationsHierarchyScale.Less:
                            MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.Less);
                            break;
                        case SituationsHierarchyScale.Little:
                            MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.Little);
                            break;
                        case SituationsHierarchyScale.Panorama:
                            MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.Panorama);
                            break;
                        case SituationsHierarchyScale.VeryLittle:
                            MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.VeryLittle);
                            break;
                    }
                    //надо первому прямоугольнику,
                    //на котором коэффициенты вычисляли,
                    //вернуть прежний размер
                    curSA.SavingScaleSituationBox.ResizeRectangle(sc);
                    curSA.SavingScaleSituationBox = null;
                }
                SaveRepository(_projectLink.Path + "\\" + _projectLink.Name + Repository.FileNameExtension);
                UpdateRibbonMainItemsAbilities();
                Status = Resources.BI_DONE;
            }
            finally
            {
                ProjectDescriptor.SetStateOfPreparationOff(stateId);
                Processing.EndWait();
            }
        }

        /// <summary>
        /// Собственно открытие проекта
        /// </summary>
        public void OpenProject(string fullName)
        {
            Guid stateId = ProjectDescriptor.SetStateOfPreparationOn(PreparationStates.Deserialization);
            try
            {
                Processing.BeginWait();
                Processing.ShowPercent(0);
                Status = Resources.BI_PROJECT_OPENING + " " + fullName;
                string path = Path.GetDirectoryName(fullName);
                string name = Path.GetFileNameWithoutExtension(fullName);
                SituationsArea beforeSH = MainFormLink.HierarchyForm.CurrentSituationsArea;
                SituationsHierarchyScale oldsc = beforeSH.Scale;
                if (oldsc != SituationsHierarchyScale.Normal)
                {
                    MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.Normal);
                }
                beforeSH.ResetSituationsArea();
                _projectLink.ResetProject(name, path, _usersList);
                Processing.ShowPercent(10);
                ProjectDescriptor openedProject = _projectLink.Open(fullName, 10, 40);
                Processing.ShowPercent(40);
                bool corrupted = true;
                if (openedProject != null)
                {
                    _projectLink = openedProject;
                    _projectLink.Path = path;
                    _projectLink.SetName(name);
                    _projectLink.Modified = false;
                    _projectLink.Active = true;
                    MainFormLink.ShowOrHideSituationsHierarchyForm(true);
                    Status = Resources.BI_SITUATIONSHIERACHY_OPENING;
                    MainFormLink.HierarchyForm.CurrentSituationsArea = new SituationsArea(this, MainFormLink.HierarchyForm);
                    Processing.ShowPercent(45);
                    MainFormLink.HierarchyForm.CurrentSituationsArea = MainFormLink.HierarchyForm.CurrentSituationsArea.Open(fullName.Replace(ProjectDescriptor.FileNameExtension, SituationsArea.FileNameExtension), 45, 65);
                    corrupted = true;
                    try
                    {
                        if (MainFormLink.HierarchyForm.CurrentSituationsArea != null)
                        {
                            corrupted = false;
                            SituationsArea curDS = MainFormLink.HierarchyForm.CurrentSituationsArea;
                            curDS.SituationsHierarchyForm = MainFormLink.HierarchyForm;
                            Processing.ShowPercent(65);
                            UpdateRibbonMainItemsAbilities();
                            MainFormLink.HierarchyForm.FocusSituationsAreaWithBrokenScrolling();
                            MainFormLink.HierarchyForm.RefreshSituationsArea();
                            SituationBox curfb = curDS.SelectedSituationBox;
                            curDS.ActualizeScheme(false, curfb);
                            curDS.SelectedSituationBox = null;
                            MainFormLink.HierarchyForm.UpdateCharacteristicsGrid(null);
                            MainFormLink.HierarchyForm.FocusSituationsAreaWithBrokenScrolling();
                            Status = Resources.BI_REPOSITORY_OPENING;
                            Processing.ShowPercent(70);
                            switch (oldsc)
                            {
                                case SituationsHierarchyScale.Less:
                                    MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.Less);
                                    break;
                                case SituationsHierarchyScale.Little:
                                    MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.Little);
                                    break;
                                case SituationsHierarchyScale.Panorama:
                                    MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.Panorama);
                                    break;
                                case SituationsHierarchyScale.VeryLittle:
                                    MainFormLink.HierarchyForm.ScaleSituationsArea(SituationsHierarchyScale.VeryLittle);
                                    break;
                            }
                            Processing.ShowPercent(80);
                            try
                            {
                                RestoreRepository(80, 99);
                            }
                            catch (Exception ex)
                            {
#if DEBUG
                                throw new BIProjectCorruptedException(ex, ex.Message);
#else
                                throw new BIProjectCorruptedException(ex, string.Empty);
#endif
                            }
                            Processing.ShowPercent(99);
                            MainFormLink.HierarchyForm.SetMode(SituationsHierarchyState.Pointer);
                            if (_IDEWindow != null)
                            {
                                _IDEWindow.Close(); //TODO такто вытягивать новую инфу надо а не закрывать
                            }
                            if (_workflowWindow != null)
                            {
                                _workflowWindow.Close();//TODO такто вытягивать новую инфу надо а не закрывать
                            }
                            _curProjectSettings.RestoreMe();
                            _treeExpanded = _curProjectSettings.ProjectExplorerTreeExpanded;
                            SelectedContainerId = _curProjectSettings.ProjectExplorerObjectsTreeSelectedContainerId;
                            _repoConnector = new RepositoryConnector();
                            _repoConnector.SetRepository(_projectLink.RepositoryLink);
                            _repoConnector.OnRefreshRepository += OnRefreshRepository;
                            //и так делается при изменении SelectedContainerLabel RefreshTree()
                            //еще круче сделать как в следующей строчке, чтобы дерево объектов то обновилось :) RefreshObjects();//хотя бы для того, чтобы отобразилась панелька дерева объектов при первом открытии проекта
                            RefreshAll();
                            UpdateCaptionName();
                        }
                    }
                    catch (BIProjectCorruptedException ex)
                    {
#if DEBUG
                        GeneralMethods.ShowUserError(ex.Message + char.ConvertFromUtf32(10) + char.ConvertFromUtf32(13) + ex.StackTrace);
#else
                        GeneralMethods.ShowUserError(ex.Message);
#endif             
                        MainFormLink.HierarchyForm.CurrentSituationsArea = null;
                        corrupted = true;
                    }
                }
                if (corrupted)
                {
                    _projectLink = new ProjectDescriptor();
                    _projectLink.CreateLIM();
                    MainFormLink.HierarchyForm.CurrentSituationsArea = new SituationsArea(this, MainFormLink.HierarchyForm);
                    MainFormLink.ShowOrHideSituationsHierarchyForm(false);
                    if (_IDEWindow != null)
                    {
                        _IDEWindow.Close(); //TODO такто вытягивать новую инфу надо а не закрывать
                    }
                    if (_workflowWindow != null)
                    {
                        _workflowWindow.Close();//TODO такто вытягивать новую инфу надо а не закрывать
                    }
                    MainFormLink.HierarchyForm.CurrentSituationsArea.SelectedSituationBox = null;
                    UpdateCaptionName(false);
                }
                Status = Resources.BI_DONE;
                Processing.ShowPercent(100);
                Processing.EndWait();
            }
            finally
            {
                ProjectDescriptor.SetStateOfPreparationOff(stateId);
            }
            MainFormLink.HierarchyForm.RefreshSituationsArea();
        }

        /// <summary>
        /// Собственно создание нового проекта
        /// </summary>
        /// <param name="name"></param>
        /// <param name="path"></param>
        public void CreateProject(string name, string path)
        {
            Status = Resources.BI_PROJECT_CREATING;
            if (!_projectLink.ResetProject(name, path, _usersList, true))
            {
                DialogResult d = GeneralMethods.ShowWarning(Resources.BI_PROJECT_DOYOUWANTSAVE_OVERWRITE, MessageBoxButtons.YesNo);
                switch (d)
                {
                    case DialogResult.Yes:
                        _projectLink.ResetProject(name, path, _usersList);
                        break;
                    case DialogResult.No:
                        MainFormLink.HierarchyForm.CenterSituationsArea();
                        return;
                }
            }
            _projectLink.RepositoryLink.InstallWorlds();
            if (!_blockAccessToAppFolder)
            {
                _projectLink.RepositoryLink.SaveMe();
            }
            _projectLink.Active = false; //чтобы Updatelinks не срабатывал
            if (!_blockAccessToAppFolder)
            {
                _projectLink.Save();
            }
            SituationsArea curDS = MainFormLink.HierarchyForm.CurrentSituationsArea;
            curDS.ResetSituationsArea();
            if (!_blockAccessToAppFolder)
            {
                curDS.Save();
            }
            _projectLink.Active = true;
            UpdateRibbonMainItemsAbilities();
            Status = Resources.BI_DONE;
            MainFormLink.ShowOrHideSituationsHierarchyForm(true);
            MainFormLink.HierarchyForm.FocusSituationsAreaWithBrokenScrolling();
            MainFormLink.HierarchyForm.RefreshMap();
            MainFormLink.HierarchyForm.CenterSituationsArea();
            if (_IDEWindow != null)
            {
                _IDEWindow.Close(); //TODO надо такто не закрывать а подтягивать новую  инфу
            }
            if (_workflowWindow != null)
            {
                _workflowWindow.Close(); //TODO надо такто не закрывать а подтягивать новую  инфу
            }
            RefreshAll();
            UpdateCaptionName();
        }

        /// <summary>
        /// Включение/отключение доступа к базовым элементам риббона
        /// </summary>        
        public void UpdateRibbonMainItemsAbilities()
        {
            if ((_projectLink != null) && !_blockRibbon)//в самый момент запуска проги проект==null
            {
                _blockRibbon = true; //иначе разные потоки сюда ломятся почему-то                
                bool isActive = _projectLink.Active;
                bool canSaveAs = isActive && !_blockAccessToAppFolder;
                bool canOpen = !_blockAccessToAppFolder;
                SaveProjectAsItem.SetState(!canSaveAs? SaveProjectAsItem.State | RibbonItemChangedStates.Disabled:SaveProjectAsItem.State & ~RibbonItemChangedStates.Disabled);
                OpenProjectItem.SetState(!canOpen ? OpenProjectItem.State | RibbonItemChangedStates.Disabled : OpenProjectItem.State & ~RibbonItemChangedStates.Disabled);
                //теперь риббоны(УШЛО В НИКУДА,Т.К. В БУДУЩЕМ ВСЕ РАВНО УБЕРУ)иерархияСитуацийToolStripMenuItem.Enabled = isActive;
                //TODO результатыПривязкиСитуацийToolStripMenuItem.Enabled = isActive;
                //TODO запускМЛВToolStripMenuItem.Enabled = isActive;                
                _blockRibbon = false;
            }
        }

        /*теперь риббоны/// <summary>
        /// Возвращает/устанавливает форму оформления
        /// </summary>
        public PreferencesDialog PreferencesForm
        {
            get
            {
                return _preferencesForm;
            }
            set
            {
                _preferencesForm = value;
            }
        }*/

        /// <summary>
        /// Возвращает/устанавливает форму настроек
        /// </summary>
        public SettingsDialog SettingsForm
        {
            get
            {
                return _settingsForm;
            }
            set
            {
                _settingsForm = value;
            }
        }

        /// <summary>
        /// Возвращает/устанавливает текущее оформление панелей
        /// </summary>       
        public PanelsStyle Style
        {
            get
            {
                return _curSettings.Style;
            }
            set
            {
                _curSettings.Style = value;
                _settingsForm.SetPanelsStyle(_curSettings.Style);                
            }
        }

        /// <summary>
        /// Возвращает/устанавливает текущую цветовую схему ситуаций
        /// </summary>       
        public ColorScheme Scheme
        {
            get
            {
                return _curSettings.Scheme;
            }
            set
            {
                _curSettings.Scheme = value;
                MainFormLink.HierarchyForm.CurrentSituationsArea.ActualizeScheme(null, true);
                MainFormLink.HierarchyForm.RefreshMap();
            }
        }

        /// <summary>
        /// Возвращает текущие настройки
        /// </summary>
        public Settings CurrentSettings
        {
            get
            {
                return _curSettings;
            }
        }

        /// <summary>
        /// Возвращает текущие настройки, относящиеся к проекту
        /// </summary>
        public ProjectSettings CurrentProjectSettings
        {
            get
            {
                return _curProjectSettings;
            }
        }

        /// <summary>
        /// Возвращает/устанавливает доступ к проигрывателю звуков
        /// </summary>
        public SoundPlayer SoundsPlayer
        {
            get
            {
                return _soundsPlayer;
            }
            set
            {
                _soundsPlayer = value;
            }
        }

        /// <summary>
        /// Отображает окно быстрого анализа
        /// </summary>
        public void ShowRapidAnalysisForm(IDateAndFactCorrelations viewingObject)
        {
            if ((viewingObject.GetCalendarDimension() == null) && (viewingObject.GetFactsDimensionsCount() < 2) 
                || (viewingObject.GetCalendarDimension() != null) && (viewingObject.GetFactsDimensionsCount() < 1))
            {
                GeneralMethods.ShowUserError(Resources.BI_RAPIDANALYSIS_ERROR_NEEDNOTLESS2DIMENSIONS);
            }
            else
            {
                foreach (RapidAnalysisForm rapid in RapidAnalysisWindows)
                {
                    if (rapid.CurrentViewingObject.Equals(viewingObject))
                    {
                        rapid.Focus();
                        return;
                    }
                }
                RapidAnalysisForm rapidanalysisform = new RapidAnalysisForm(this, viewingObject);
                rapidanalysisform.Show();                
                RapidAnalysisWindows.Add(rapidanalysisform);
            }
        }

        /// <summary>
        /// Восстанавливает репозиторий
        /// </summary>
        private void RestoreRepository(int minPercent, int maxPercent)
        {
            foreach (RapidAnalysisForm rapid in RapidAnalysisWindows)
            {
                rapid.Close();
            }
            RapidAnalysisWindows = new List<RapidAnalysisForm>();
            Processing.ShowPercent(minPercent);
            string fname = ProjectLink.Path + "\\" + ProjectLink.Name + Repository.FileNameExtension;
            Processing.ShowPercent(minPercent + 1);
            ProjectLink.RepositoryLink.RestoreMe(fname, minPercent + 1, maxPercent);
            Processing.ShowPercent(maxPercent);
        }

        /// <summary>
        /// Возвращает/устанавливает список форм быстрого анализа
        /// </summary>
        public ICollection<RapidAnalysisForm> RapidAnalysisWindows
        {
            get
            {
                return _rapidAnalysisWindows;
            }
            set
            {
                _rapidAnalysisWindows = value;
            }
        }

        /// <summary>
        /// Возвращает/устанавливает окно системы документооборота
        /// </summary>
        public WorkflowForm WorkflowWindow
        {
            get
            {
                return _workflowWindow;
            }
            set
            {
                _workflowWindow = value;
            }
        }

        /// <summary>
        /// Возвращает/устанавливает окно среды разработки
        /// </summary>
        public IDEForm IDEWindow
        {
            get
            {
                return _IDEWindow;
            }
            set
            {
                _IDEWindow = value;
            }
        }

        /// <summary>
        /// Возвращает/устанавливает связь с текущим проектом
        /// </summary>
        public ProjectDescriptor ProjectLink
        {
            get
            {
                return _projectLink;
            }
            set
            {
                _projectLink = value;
            }
        }

        /// <summary>
        /// Обновляет возможности по внешнему виду объектов
        /// </summary>
        private void UpdateViewAbilities(bool isTreeCall)
        {
            bool isHierarchyVisible = VisibleTypes.Kind == MetadataObjectKind.Situation;                        
            bool isShort = ObjectsList.View == View.LargeIcon;
            bool isFull = ObjectsList.View == View.Details;
            краткаяИнформацияToolStripMenuItem.Visible = !isTreeCall && !isHierarchyVisible;
            подробнаяИнформацияToolStripMenuItem.Visible = !isTreeCall && !isHierarchyVisible;
            краткаяИнформацияToolStripMenuItem.Checked = isShort;
            подробнаяИнформацияToolStripMenuItem.Checked = isFull;            
            ShortInfoButton.SetState(isShort ? ShortInfoButton.State | RibbonItemChangedStates.Checked : ShortInfoButton.State & ~RibbonItemChangedStates.Checked);
            FullInfoButton.SetState(isFull ? FullInfoButton.State | RibbonItemChangedStates.Checked : FullInfoButton.State & ~RibbonItemChangedStates.Checked);            
            объектыТолькоИзВыбраннойПапкиToolStripMenuItem1.Visible = !isHierarchyVisible;
            ObjectsTreeEnabledSeparator.Visible = !isHierarchyVisible;
            TogglePropertiesButton.SetState(ObjectPropertiesArea.Visible ? TogglePropertiesButton.State | RibbonItemChangedStates.Checked : TogglePropertiesButton.State & ~RibbonItemChangedStates.Checked);
            ToggleVisibleObjectsButton.SetState(ObjectsGroupTabControl.Visible ? ToggleVisibleObjectsButton.State | RibbonItemChangedStates.Checked : ToggleVisibleObjectsButton.State & ~RibbonItemChangedStates.Checked);
            SetRibbonViewKind(ObjectKindsView.SelectedItems[0].Index);            
            _metadataTabs.Actual = !isHierarchyVisible;            
        }

        /// <summary>
        /// Обработка выбора пункта создания объекта
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NewObjectClick(object sender, EventArgs e)
        {
            ShowCreateObjectDialog((MetadataObjectKind)(sender as ToolStripItem).Tag);
        }

        /// <summary>
        /// Обновление списка создаваемых объектов
        /// </summary>
        private void FillCreateObjectList(ToolStripItemCollection menuCollection)
        {
            menuCollection.Clear();
            ToolStripItem pr = null;
            MetadataObjectKind kind = MetadataObjectKind.Folder;
            if (IsTreeEnabled)
            {
                pr = menuCollection.Add(kind.ToUserString(true) + "...");
                pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
                pr.Tag = kind;
                pr.Click += new EventHandler(NewObjectClick);
            }
            kind = MetadataObjectKind.Indicator;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            pr.Click += new EventHandler(NewObjectClick);
            kind = MetadataObjectKind.Table;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            pr.Click += new EventHandler(NewObjectClick);
            kind = MetadataObjectKind.Dimension;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            pr.Click += new EventHandler(NewObjectClick);
            kind = MetadataObjectKind.Cube;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            pr.Click += new EventHandler(NewObjectClick);
            kind = MetadataObjectKind.TimeSeries;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            pr.Click += new EventHandler(NewObjectClick);
            kind = MetadataObjectKind.Model;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            pr.Click += new EventHandler(NewObjectClick);
            kind = MetadataObjectKind.Calculation;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            kind = MetadataObjectKind.ClassificationProblem;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            pr.Click += new EventHandler(NewObjectClick);
            kind = MetadataObjectKind.ActionSet;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            pr.Click += new EventHandler(NewObjectClick);
            kind = MetadataObjectKind.Shortcut;
            pr = menuCollection.Add(kind.ToUserString(true) + "...");
            pr.Image = kind.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            pr.Tag = kind;
            pr.Click += new EventHandler(NewObjectClick);
        }

        /// <summary>
        /// Устанавливает черную тему риббонов
        /// </summary>
        /// <param name="isBlack"></param>
        public void SetRibbonsBlackTheme(bool isBlack)
        {
            //пока что только в самом Обозревателе Проекта есть риббон, так что меняем только его
            ProjectExplorerRibbon.BlackTheme = isBlack;            
        }

        /// <summary>
        /// Обновляет возможности по манипулированию с объектами
        /// </summary>
        /// <returns>вызов произведен из дерева контейнерных объектов?</returns>
        private bool UpdateAvailableActions()
        {
            int c = ObjectsList.SelectedItems.Count;
            bool isTreeCall = ObjectsTree.Focused;
            bool isFictiveProjectFolderSelected = (ObjectsTree.Nodes.Count > 0) && (ObjectsTree.SelectedNode == ObjectsTree.Nodes[0]);
            bool isFictiveProjectFolderCall = isTreeCall && isFictiveProjectFolderSelected;
            bool isAnySelected = isTreeCall || (c > 0);
            bool isOneSelected = isAnySelected && (c == 1);
            MetadataObjectKind firstKind = 
                isAnySelected ? 
                    isTreeCall ? MetadataObjectKind.Folder : ((MetadataObjectDescriptor)ObjectsList.SelectedItems[0].Tag).Kind 
                    : MetadataObjectKind.None;
            bool isTable = !isTreeCall && isOneSelected && (firstKind == MetadataObjectKind.Table);
            bool isCube = !isTreeCall && isOneSelected && (firstKind == MetadataObjectKind.Cube);
            bool isTimeseries = !isTreeCall && isOneSelected && (firstKind == MetadataObjectKind.TimeSeries);
            bool isShortcut = !isTreeCall && isOneSelected && (firstKind == MetadataObjectKind.Shortcut);
            bool isActionSet = !isTreeCall && isOneSelected && (firstKind == MetadataObjectKind.ActionSet);
            bool isNotOpened = !isTreeCall && isOneSelected && false;//нет таких пока что (kind == MetadataObjectKind.Calculation);
            bool isAllObjectsVisible = VisibleTypes.All;
            bool isHierarchyVisible = VisibleTypes.Kind == MetadataObjectKind.Situation;
            //**********
            //Проверяю далее !_inObjectF2Renaming, чтобы Del при переименовании объектов работал
            //удалитьToolStripMenuItem.Visible = !_inObjectF2Renaming && isAnySelected && !isFictiveProjectFolderSelected;
            удалитьToolStripMenuItem1.Visible = !_inObjectF2Renaming && isAnySelected && !isFictiveProjectFolderCall;
            //удалитьToolStripMenuItem.Enabled = !_inObjectF2Renaming &&isAnySelected && !isFictiveProjectFolderSelected;//без этого работают горячие клавиши
            DeleteButton.SetState(!_inObjectF2Renaming && isAnySelected && !isFictiveProjectFolderCall ? DeleteButton.State & ~RibbonItemChangedStates.Disabled : DeleteButton.State | RibbonItemChangedStates.Disabled);
            удалитьToolStripMenuItem1.Enabled = !_inObjectF2Renaming && isAnySelected && !isFictiveProjectFolderCall;//без этого работают горячие клавиши
            //**********
            открытьToolStripMenuItem.Visible =  isOneSelected && !isNotOpened;
            //открытьToolStripMenuItem1.Visible = isOneSelected && !isNotOpened;
            открытьToolStripMenuItem.Enabled = isOneSelected && !isNotOpened;//без этого работают горячие клавиши
            //открытьToolStripMenuItem1.Enabled = isOneSelected && !isNotOpened;//без этого работают горячие клавиши
            OpenObjectButton.SetState(isOneSelected && !isNotOpened ? OpenObjectButton.State & ~RibbonItemChangedStates.Disabled : OpenObjectButton.State | RibbonItemChangedStates.Disabled);            
            создатьСсылкуToolStripMenuItem1.Visible = !isShortcut && isOneSelected && !isNotOpened && !isTreeCall;
            //создатьСсылкуToolStripMenuItem.Enabled = !isShortcut && isOneSelected && !isNotOpened && !isTreeCall;//без этого работают горячие клавиши
            AttachShortcutButton.SetState(!isShortcut && isOneSelected && !isNotOpened && !isTreeCall ? AttachShortcutButton.State & ~RibbonItemChangedStates.Disabled : AttachShortcutButton.State | RibbonItemChangedStates.Disabled);
            создатьСсылкуToolStripMenuItem1.Enabled = !isShortcut && isOneSelected && !isNotOpened && !isTreeCall;//без этого работают горячие клавиши
            //перейтиКОбъектуToolStripMenuItem.Visible = isShortcut;
            перейтиКОбъектуToolStripMenuItem1.Visible = isShortcut;
            переименоватьToolStripMenuItem.Visible = isOneSelected && (!isTreeCall || !isFictiveProjectFolderSelected);
            //переименоватьToolStripMenuItem1.Visible = isOneSelected && (!isTreeCall || !isFictiveProjectFolderSelected);
            переименоватьToolStripMenuItem.Enabled = isOneSelected && (!isTreeCall || !isFictiveProjectFolderSelected);//без этого работают горячие клавиши
            //переименоватьToolStripMenuItem1.Enabled = isOneSelected && (!isTreeCall || !isFictiveProjectFolderSelected);//без этого работают горячие клавиши            
            RenameButton.SetState(isOneSelected && (!isTreeCall || !isFictiveProjectFolderSelected) ? RenameButton.State & ~RibbonItemChangedStates.Disabled : RenameButton.State | RibbonItemChangedStates.Disabled);
            RenameLinetoolStripMenuItem1.Visible = isOneSelected && (!isTreeCall || !isFictiveProjectFolderSelected);
            ImportDataLinetoolStripMenuItem1.Visible = isOneSelected && (!isTreeCall || !isFictiveProjectFolderSelected);            
            импортироватьДанныеToolStripMenuItem.Visible = !isTreeCall && isOneSelected && (isCube || isTable || isTimeseries);            
            ImportActsLine.Visible = !isTreeCall && isOneSelected && (isTable || isCube || isTimeseries);
            ImportActsLine2.Visible = !isTreeCall && isOneSelected && (isTable || isCube || isTimeseries);            
            создатьНовыйОбъектToolStripMenuItem.Visible = !isTreeCall && !isHierarchyVisible;
            создатьНовыйОбъектToolStripMenuItem.Enabled = !isTreeCall && !isHierarchyVisible;
            ViewTypeSeparator.Visible = !isTreeCall && !isHierarchyVisible;
            FindLineStripMenuItem2.Visible = !isHierarchyVisible;
            if (isAllObjectsVisible && !isTreeCall)
            {                
                создатьНовыйОбъектToolStripMenuItem.ShortcutKeys = Keys.None;                
                создатьНовыйОбъектToolStripMenuItem.Text = Resources.BI_PROJECTEXPLORER_CREATECAPTION_OBJECT;
                FillCreateObjectList(создатьНовыйОбъектToolStripMenuItem.DropDownItems);                
                создатьНовуюПапкуToolStripMenuItem1.Visible = false;
            }
            else
            {
                if (!isTreeCall)
                {                    
                    создатьНовыйОбъектToolStripMenuItem.ShortcutKeys = Keys.Insert;                    
                    создатьНовыйОбъектToolStripMenuItem.DropDownItems.Clear();
                    string objectName = string.Empty;
                    switch (VisibleTypes.Kind)
                    {
                        case MetadataObjectKind.Indicator:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_INDICATOR;
                            break;
                        case MetadataObjectKind.Table:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_TABLE;
                            break;
                        case MetadataObjectKind.Dimension:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_DIMENSION;
                            break;
                        case MetadataObjectKind.Cube:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_CUBE;
                            break;
                        case MetadataObjectKind.TimeSeries:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_TIMESERIES;
                            break;
                        case MetadataObjectKind.Model:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_MODEL;
                            break;
                        case MetadataObjectKind.Calculation:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_CALCULATION;
                            break;
                        case MetadataObjectKind.ClassificationProblem:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_CLASSIFICATIONPROBLEM;
                            break;
                        case MetadataObjectKind.ActionSet:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_ACTIONSET;
                            break;
                        case MetadataObjectKind.Shortcut:
                            objectName = Resources.BI_PROJECTEXPLORER_CREATECAPTION_SHORTCUT;
                            break;
                    }                    
                    создатьНовыйОбъектToolStripMenuItem.Text = objectName;
                }                
                создатьНовуюПапкуToolStripMenuItem1.Visible = !isHierarchyVisible;// && IsTreeEnabled;
            }
            //CreateFolderButton.SetState(isHierarchyVisible || !IsTreeEnabled ? CreateFolderButton.State | RibbonItemChangedStates.Disabled : CreateFolderButton.State & ~RibbonItemChangedStates.Disabled);
            bool canCopy = isTreeCall && !isFictiveProjectFolderCall || !isTreeCall && isAnySelected;
            bool canCut = canCopy;
            bool goodClipboard = Clipboard.GetDataObject().GetDataPresent(typeof(Guid))
                || Clipboard.GetDataObject().GetDataPresent(typeof(Guid[]));
            CutButton.SetState(!canCut ? CutButton.State | RibbonItemChangedStates.Disabled : CutButton.State & ~RibbonItemChangedStates.Disabled);
            CutContextMenuItem.Enabled = isTreeCall && !isFictiveProjectFolderCall || !isTreeCall && isAnySelected;            
            CopyButton.SetState(!canCopy ? CopyButton.State | RibbonItemChangedStates.Disabled : CopyButton.State & ~RibbonItemChangedStates.Disabled);
            CopyContextMenuItem.Enabled = canCopy;
            PasteButton.SetState(!goodClipboard ? PasteButton.State | RibbonItemChangedStates.Disabled : PasteButton.State & ~RibbonItemChangedStates.Disabled);
            PasteContextMenuItem.Enabled = goodClipboard;
            bool canSelectAll = !isTreeCall;
            SelectAllButton.SetState(!canSelectAll ? SelectAllButton.State | RibbonItemChangedStates.Disabled : SelectAllButton.State & ~RibbonItemChangedStates.Disabled);
            SelectAllContextMenuItem.Enabled = canSelectAll;
            UpFolderButton.SetState(isFictiveProjectFolderSelected || !IsTreeEnabled ? UpFolderButton.State | RibbonItemChangedStates.Disabled : UpFolderButton.State & ~RibbonItemChangedStates.Disabled);
            ////
            string findText = string.Format(Resources.BI_PROJECTEXPLORER_FIND_CAPTION, VisibleTypes.Kind.ToUserString(true));
            //SearchToolStripButton.Text = findText;
            //теперь риббоны найтиToolStripMenuItem.Text = findText + "...";
            найтиToolStripMenuItem1.Text = findText + "...";            
            ///
            свойстваToolStripMenuItem.Visible = !isTreeCall & isOneSelected;
            //свойстваToolStripMenuItem1.Visible = !isTreeCall & isOneSelected;
            PropertiesSeparator.Visible = !isTreeCall & isOneSelected;
            PropertiesSeparator2.Visible = !isTreeCall & isOneSelected;
            свойстваToolStripMenuItem.Checked = ObjectPropertiesArea.Visible;            
            //свойстваToolStripMenuItem1.Checked = ObjectPropertiesArea.Visible;
            ///контекстные вкладки риббоны
            _situationsTabs.Actual = isHierarchyVisible;
            _shortcutsTabs.Actual = isShortcut;
            _actionsetsTabs.Actual = isActionSet;
            _dataTabs.Actual = isCube || isTable || isTimeseries;
            ///
            return isTreeCall;
        }

        /// <summary>
        /// Обновляет возможные действия по перемещению в истории
        /// </summary>
        private void UpdateAvailableHistoryActions()
        {
            if (_objectsHistory == null)
                return; //еще не проинициализировали историю
            bool noHistory = _objectsHistory.Count <= 1;
            bool inHistory = !noHistory && (_historyFocus < _objectsHistory.Count - 1);
            bool backHistoryEnabled = !noHistory && (_historyFocus > 0);
            bool isHierarchyVisible = VisibleTypes.Kind == MetadataObjectKind.Situation;
            BackNavigationButton.SetState(backHistoryEnabled ? BackNavigationButton.State & ~RibbonItemChangedStates.Disabled : BackNavigationButton.State | RibbonItemChangedStates.Disabled);            
            ForwardNavigationButton.SetState(inHistory ? ForwardNavigationButton.State & ~RibbonItemChangedStates.Disabled : ForwardNavigationButton.State | RibbonItemChangedStates.Disabled);            
        }

        /// <summary>
        /// Вызывает диалог извлечения данных в выделенный объект репозитория
        /// </summary>
        private void ShowDataExtractionDialog(bool intoSelectedObject)
        {
            if (intoSelectedObject)
            {
                var info = (MetadataObjectDescriptor)(ObjectsList.SelectedItems[0].Tag);
                ShowDataExtractionDialog(info);
            }
            else
                ShowDataExtractionDialog();
        }

        /// <summary>
        /// Показывает содержимое временного ряда
        /// </summary>
        /// <param name="series"></param>
        public void ShowTimeSeries(ITimeSeries series)
        {
            SelectActiveCalculationDialog sacd = new SelectActiveCalculationDialog(ProjectLink, series);
            if (sacd.ShowDialog() != DialogResult.OK)
                return;
            series.ActiveCalculation = sacd.ActiveCalculation;            
            ShowRapidAnalysisForm(series);
        }

        /// <summary>
        /// Открывает указанный объект
        /// </summary>
        /// <param name="metadataObject"></param>
        public void OpenObject(IMetadataObject metadataObject)
        {
            switch (metadataObject.Kind)
            {
                case MetadataObjectKind.Folder:
                    FocusObject(metadataObject, MetadataObjectsHistoryPointKind.OpenedContainerObject);
                    break;
                case MetadataObjectKind.Indicator:                    
                    IndicatorEditorDialog ieForm = new IndicatorEditorDialog(_projectLink, metadataObject as IIndicator);
                    ieForm.ShowDialog();
                    break;
                case MetadataObjectKind.Table:
                    TableViewerDialog tvForm = new TableViewerDialog(metadataObject as ITable);
                    tvForm.ShowDialog();
                    break;
                case MetadataObjectKind.Dimension:                    
                    DimensionViewerForm dvForm = new DimensionViewerForm(metadataObject as IDimension);
                    dvForm.ShowDialog();
                    break;
                case MetadataObjectKind.TimeSeries:
                    ShowTimeSeries(metadataObject as ITimeSeries);
                    break;
                case MetadataObjectKind.Cube:
                    ShowRapidAnalysisForm(metadataObject as IDateAndFactCorrelations);
                    break;
                case MetadataObjectKind.Model:                    
                    ModelEditorDialog med = new ModelEditorDialog(ProjectLink, metadataObject as IModel);
                    med.ShowDialog();
                    break;
                case MetadataObjectKind.Calculation:                    
                    CalculationRunDialog calcrun = new CalculationRunDialog(this, metadataObject as ICalculation);
                    calcrun.ShowDialog();
                    break;
                case MetadataObjectKind.ClassificationProblem:                    
                    switch ((ClassificationProblemKind)metadataObject.Subkind)
                    {
                        case ClassificationProblemKind.WithTraining:
                            ClassificationProblemWithTrainingRunDialog cprun = new ClassificationProblemWithTrainingRunDialog(this, metadataObject as IClassificationProblemWithTraining);
                            cprun.ShowDialog();
                            break;
                        default:
                            Assert.Fail(Assert.Id.Assert00304);
                            break;
                    }
                    break;
                case MetadataObjectKind.ActionSet:                    
                    ShowIDEWindow(metadataObject as IActionSet);
                    break;
                case MetadataObjectKind.Shortcut:                    
                    OpenShortcut(metadataObject as IShortcut);
                    break;
                default:
                    Assert.Fail(Assert.Id.Assert00122);
                    break;
            }            
        }

        /// <summary>
        /// Открывает указанный объект
        /// </summary>
        /// <param name="desc"></param>
        public void OpenObject(IMetadataObjectDescriptor desc)
        {
            OpenObject(ProjectLink.RepositoryLink.GetObjectDescriptorById(desc.Id).Bind());
        }

        /// <summary>
        /// Открывает выделенный объект
        /// </summary>
        private void OpenSelectedObject()
        {            
            if (ObjectsTree.Focused)
            {
                SelectedContainerId = ((MetadataObjectDescriptor)ObjectsTree.SelectedNode.Tag).Id;
                return;
            }
            ListView.SelectedListViewItemCollection sel = ObjectsList.SelectedItems;
            if (sel.Count != 1)
                return;            
            ListViewItem item = sel[0];
            MetadataObjectDescriptor info = (MetadataObjectDescriptor)item.Tag;
            OpenObject(info);            
        }

        /// <summary>
        /// Открывает ссылку
        /// </summary>
        /// <param name="shortcut"></param>
        private void OpenShortcut(IShortcut shortcut)
        {
            switch(shortcut.GetShortcutType())
            {
                case ShortcutType.None:
                    GeneralMethods.ShowUserError(string.Format(Resources.BI_PROJECTEXPLORER_SHORTCUT_NOAIM, shortcut.ToString()));
                    return;                    
                case ShortcutType.MetadataObject:
                    OpenObject((MetadataObjectDescriptor)shortcut.GetAim());
                    break;
                default:
                    Assert.Fail(Assert.Id.Assert00123);
                    break;
            }
        }

        /// <summary>
        /// Вводит выделенный объект в состояние переименования
        /// </summary>
        private void StartObjectRenaming()
        {
            if (ObjectsList.Focused)
            {
                ObjectsList.SelectedItems[0].BeginEdit();
            }
            else
            {
                ObjectsTree.SelectedNode.BeginEdit();
            }
        }

        /// <summary>
        /// Завершает переименование объекта
        /// </summary>
        private bool EndObjectRenaming(int objectIndex, string newName/*, bool isThroughNameBox*/)
        {
            if (newName == null)
                return false;//отмена редактирования            
            ListViewItem item = ObjectsList.Items[objectIndex];
            IMetadataObjectDescriptor desc = item.Tag as IMetadataObjectDescriptor;
            string oldname = desc.Name;
            string itemlabel = desc.Label;
            if (newName != oldname)
            {
                try
                {
                    newName = newName.Trim();
                    if (string.IsNullOrEmpty(newName))
                    {
                        throw new BIMetadataObjectEmptyNameException(null);
                    }
                }
                catch (BIMetadataObjectEmptyNameException ex)
                {
                    GeneralMethods.ShowUserError(ex.Message);
                    /*if (isThroughNameBox)
                    {
                        SelectedObjectNameBox.Text = oldname;
                    }*/
                    return false;
                }
                _blockObjectsListAutoRefresh = true; //иначе глюки будут в листвью
                desc.SetName(newName);
                _blockObjectsListAutoRefresh = false;
                switch (desc.Kind)
                {
                    case MetadataObjectKind.ActionSet:
                        UpdateActionSetWindowCaption(_projectLink.RepositoryLink.GetObjectDescriptorById(desc.Id).Bind() as IActionSet);
                        break;
                    default:
                        break;
                }
                /*больше не нужно 28.12.2010int index = 0;                
                while ((index = _objectsHistory.IndexOf(desc, index)) != -1)
                {
                    MetadataObjectsHistoryPoint histItem = _objectsHistory[index];
                    histItem.SetNewName(newName);
                    _objectsHistory[index] = histItem;
                }
                desc.Name = newName;                
                item.Tag = desc;                */
            }                        
            return true;
        }

        /// <summary>
        /// Завершает смену ярлыка объекта
        /// </summary>
        private bool EndObjectRelabeling(int objectIndex, string newLabel)
        {
            if (newLabel == null)
                return false;//отмена редактирования            
            ListViewItem item = ObjectsList.Items[objectIndex];
            IMetadataObjectDescriptor desc = item.Tag as IMetadataObjectDescriptor;
            string oldlabel = desc.Label;
            if (newLabel != oldlabel)
            {
                try
                {
                    ProjectLink.RepositoryLink.IsNewLabelCorrect(newLabel, true);                    
                }
                catch (BIMetadataObjectIncorrectLabelException ex)
                {
                    GeneralMethods.ShowUserError(ex.Message);
                    SelectedObjectLabelBox.Text = oldlabel;
                    return false;
                }                
                desc.SetLabel(newLabel);                
                switch (desc.Kind)
                {                    
                    case MetadataObjectKind.Table:                        
                        //переименовываем ссылки на таблицу во всех характеристиках
                        INamedHierarchy<Characteristic> tableCharacteristics = _projectLink.GetAllTableCharacteristicsByTableLabel(oldlabel);
                        foreach (Characteristic ch in tableCharacteristics)
                        {
                            ch.SetExpectedValue(newLabel);
                        }
                        break;                    
                    case MetadataObjectKind.Cube:                        
                        //переименовываем ссылки на куб во всех характеристиках
                        INamedHierarchy<Characteristic> cubeCharacteristics = _projectLink.GetAllCubeOrTimeSeriesCharacteristicsByLabel(oldlabel);
                        foreach (Characteristic ch in cubeCharacteristics)
                        {
                            ch.SetExpectedValue(newLabel);
                        }
                        break;
                    case MetadataObjectKind.TimeSeries:                        
                        //переименовываем ссылки на ряд во всех характеристиках
                        INamedHierarchy<Characteristic> seriesCharacteristics = _projectLink.GetAllCubeOrTimeSeriesCharacteristicsByLabel(oldlabel);
                        foreach (Characteristic ch in seriesCharacteristics)
                        {
                            ch.SetExpectedValue(newLabel);
                        }
                        break;                    
                    case MetadataObjectKind.ActionSet:
                        //переименовываем ссылки на свод действий во всех характеристиках
                        INamedHierarchy<Characteristic> actionsetCharacteristics = _projectLink.GetAllActionSetCharacteristicsByActionSetLabel(oldlabel);
                        foreach (Characteristic ch in actionsetCharacteristics)
                        {
                            ch.SetExpectedValue(newLabel);
                        }
                        break;                    
                }
                /*больше не надоint index = 0;
                while ((index = _objectsHistory.IndexOf(desc, index)) != -1)
                {
                    MetadataObjectsHistoryPoint histItem = _objectsHistory[index];
                    histItem.SetNewLabel(newLabel);
                    _objectsHistory[index] = histItem;
                }                
                desc.Label = newLabel;                
                item.Tag = desc;*/
            }            
            UpdateObjectProperties();
            return true;
        }

        /// <summary>
        /// Предобработчик удаления объектов
        /// </summary>
        /// <returns></returns>
        public bool DeletePreprocessor(List<IMetadataObjectDescriptor> descs)
        {
            int c = descs.Count;
            for (int i = 0; i < c; i++)
            {
                switch (descs[i].Kind)
                {
                    case MetadataObjectKind.ActionSet:
                        IActionSet actset = descs[i].Bind() as IActionSet;
                        if (!CloseActionSetWindow(actset))
                            return false;
                        break;
                    default:
                        break;
                }                
            }
            return true;
        }

        /// <summary>
        /// Обрабатывает событие обновления репозитория из соединителя с репозиторием
        /// </summary>
        private void OnRefreshRepository(object sender, EventArgs args)
        {
            if (!_blockObjectsListAutoRefresh)
            {
                RefreshTree();
                RefreshObjects();
                UpdateObjectProperties();
            }
        }

        /// <summary>
        /// Удаляет указанные объекты
        /// </summary>
        private void DeleteObjects(List<IMetadataObjectDescriptor> descs)
        {            
            if (_repoConnector.DeleteObjects(descs, DeletePreprocessor, false))
            {
                //тут по идее надо вызывать OnRefreshRepository, но он и так вызовется из _repoConnector.DeleteObjects
            }
        }

        /// <summary>
        /// Удаляет выделенные объекты
        /// </summary>
        private void DeleteSelectedObjects()
        {
            if (_inObjectF2Renaming)
                return;//чтобы кнопка Del работала при переименовании объектов
            List<IMetadataObjectDescriptor> descs = new List<IMetadataObjectDescriptor>();            
            if (ObjectsTree.Focused)
            {
                IMetadataObjectDescriptor desc = ObjectsTree.SelectedNode.Tag as IMetadataObjectDescriptor;
                descs.Add(desc);                
            }
            else
            {
                ListView.SelectedListViewItemCollection sel = ObjectsList.SelectedItems;
                int c = sel.Count;
                for (int i = 0; i < c; i++)
                {
                    IMetadataObjectDescriptor info = sel[i].Tag as IMetadataObjectDescriptor;
                    descs.Add(info);
                }                
            }
            DeleteObjects(descs);
        }

        /// <summary>
        /// Отображает диалог создания объекта
        /// </summary>
        private void ShowCreateObjectDialog()
        {
            ShowCreateObjectDialog(VisibleTypes.Kind);
        }

        /// <summary>
        /// Отображает диалог создания модели
        /// </summary>
        private void ShowCreateObjectDialog(ModelType kind)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Model, (int)kind);
        }

        /// <summary>
        /// Отображает диалог создания измерения
        /// </summary>
        private void ShowCreateObjectDialog(DimensionKind kind)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Dimension, (int)kind);
        }

        /// <summary>
        /// Отображает диалог создания объекта
        /// </summary>
        private void ShowCreateObjectDialog(MetadataObjectKind kind)
        {
            ShowCreateObjectDialog(kind, 0);
        }

        /// <summary>
        /// Отображает диалог создания объекта
        /// </summary>
        private void ShowCreateObjectDialog(MetadataObjectKind kind, int subKind)
        {
            if ((VisibleTypes.Kind != kind) && !VisibleTypes.All)
            {
                VisibleTypes = new MetadataObjectsVisibleTypes()
                {
                    Kind = MetadataObjectKind.None,
                    All = true
                };
            }
            switch (kind)
            {
                case MetadataObjectKind.Folder:
                    if (!IsTreeEnabled)
                        SetTreeEnable(true);
                    break;
                case MetadataObjectKind.Indicator:
                case MetadataObjectKind.Table:
                case MetadataObjectKind.Dimension:
                case MetadataObjectKind.Cube:
                case MetadataObjectKind.TimeSeries:
                case MetadataObjectKind.Model:
                case MetadataObjectKind.Calculation:
                case MetadataObjectKind.ClassificationProblem:
                case MetadataObjectKind.ActionSet:
                case MetadataObjectKind.Shortcut:
                    break;
                default:
                    Assert.Fail(Assert.Id.Assert00247);
                    break;
            }       
            CreateObjectDialog newObjectDialog = null;
            IMetadataObjectDescriptor parent = _projectLink.RepositoryLink.GetObjectDescriptorById(SelectedContainerId);            
            if ((kind == MetadataObjectKind.ClassificationProblem) && (subKind != 0))
                newObjectDialog = new CreateObjectDialog(this, (ClassificationProblemKind)subKind, parent);
            else
            {
                if ((kind == MetadataObjectKind.Model) && (subKind != 0))
                    newObjectDialog = new CreateObjectDialog(this, (ModelType)subKind, parent);
                else
                {
                    if ((kind == MetadataObjectKind.Dimension) && (subKind != 0))
                        newObjectDialog = new CreateObjectDialog(this, (DimensionKind)subKind, parent);
                    else
                        if ((kind == MetadataObjectKind.Indicator) && (subKind != 0))
                            newObjectDialog = new CreateObjectDialog(this, (IndicatorType)subKind, parent);
                        else
                            newObjectDialog = new CreateObjectDialog(this, kind, parent);
                }
            }
            if (newObjectDialog.ShowDialog() == DialogResult.OK)
            {
                RefreshTree();
                RefreshObjects();
                foreach (ListViewItem item in ObjectsList.Items)
                {
                    item.Selected = ((MetadataObjectDescriptor)item.Tag).Id == newObjectDialog.CreatedObject.Id;
                }
            }
        }

        /// <summary>
        /// Заполняет дерево контейнерных объектов
        /// </summary>
        /// <param name="headNode"></param>
        /// <param name="headDescriptor"></param>
        private void FillTree(TreeNode headNode, IMetadataObjectDescriptor headDescriptor)
        {
            foreach (IMetadataObjectDescriptor desc in _projectLink.RepositoryLink.GetObjectsDescriptors(headDescriptor.Id, MetadataObjectKind.Folder))
            {
                headNode.Nodes.Add(desc.Id.ToString(), desc.Name);
                TreeNode currentNode = headNode.Nodes[headNode.Nodes.Count - 1];
                currentNode.Tag = desc;
                if (desc.Id == SelectedContainerId)
                {
                    ObjectsTree.SelectedNode = currentNode;
                    ObjectsTree.SelectedNode.EnsureVisible();
                    //надо раскрыть выделенную вершину (EnsureVisible не катит, не раскрывает, по
                    //крайней мере если вершин в дереве меньше, чем высота трилиста)            
                    TreeNode curNode = currentNode;
                    while (curNode.Parent != null)
                    {
                        curNode = curNode.Parent;
                        Guid id = ((MetadataObjectDescriptor)curNode.Tag).Id;
                        if (!_treeExpanded.Contains(id))
                        {
                            _treeExpanded.Add(id);
                        }
                    }            
                }
                if (_cuttedItemsDescriptors.Contains(desc))
                {
                    currentNode.ForeColor = SystemColors.GrayText;
                }
                FillTree(currentNode, desc);
                if (_treeExpanded.Contains(desc.Id))
                {
                    currentNode.Expand();
                }
                else
                {
                    currentNode.Collapse();
                }
            }
        }

        /// <summary>
        /// Обновляет дерево контейнерных объектов
        /// </summary>
        private void RefreshTree()
        {
            _programTreeBuild = true;
            ObjectsTree.BeginUpdate();
            while (true)
            {                
                ObjectsTree.Nodes.Clear();
                if (!_projectLink.Active)
                    break;
                IMetadataObjectDescriptor desc = _projectLink.RepositoryLink.RootFolder.Descriptor;
                ObjectsTree.Nodes.Add(desc.Id.ToString(), desc.Name);
                TreeNode headNode = ObjectsTree.Nodes[ObjectsTree.Nodes.Count - 1];                
                headNode.Tag = desc;
                if (SelectedContainerId == desc.Id)
                {
                    ObjectsTree.SelectedNode = headNode;
                }                
                if (_cuttedItemsDescriptors.Contains(desc))
                {
                    headNode.ForeColor = SystemColors.GrayText;
                }                
                FillTree(headNode, desc);
                if (ObjectsTree.SelectedNode == null) //бывает если SelectedContainerLabel некорректный (из реестра прочитали попорченный)
                {
                    ObjectsTree.SelectedNode = headNode;
                }
                headNode.Expand();                                    
                break;
            }
            ObjectsTree.EndUpdate();               
            _programTreeBuild = false;
            //чистка устаревших сведений о контейнерах (уже удаленных)
            List<Guid> toDelete = new List<Guid>();
            foreach (Guid id in _treeExpanded)
            {
                if (_projectLink.RepositoryLink.GetObjectDescriptorById(id) == null)
                    toDelete.Add(id);
            }
            foreach(Guid id in toDelete)
            {
                _treeExpanded.Remove(id);
            }
        }

        /// <summary>
        /// Обновляет список объектов
        /// </summary>
        private void RefreshObjects()
        {
            ObjectsList.BeginUpdate();
            while (true)
            {
                ListView.ListViewItemCollection items = ObjectsList.Items;
                items.Clear();
                if ((VisibleTypes.Kind == MetadataObjectKind.Situation) || !_projectLink.Active)
                {
                    //PathBox.Visible = false;
                    //ObjectsTreeTab.PageVisible = false;
                    break;
                }
                //ObjectsTreeTab.PageVisible = true;
                TreeNode lookNode = IsTreeEnabled ? ObjectsTree.SelectedNode : ObjectsTree.Nodes[0];
                PathBox.Text = lookNode.FullPath;
                //PathBox.Visible = true;
                IEnumerable<IMetadataObjectDescriptor> objectsList = null;
                MetadataObjectKind showKind = IsTreeEnabled ? MetadataObjectKind.Folder : VisibleTypes.Kind; //папки показывать в режиме отключенного дерева нет смысла
                while (true)
                {
                    if (VisibleTypes.All && (showKind != MetadataObjectKind.Folder))
                    {
                        objectsList = IsTreeEnabled ? ProjectLink.RepositoryLink.GetObjectsDescriptors((lookNode.Tag as IMetadataObjectDescriptor).Id) : ProjectLink.RepositoryLink.GetObjectsDescriptors();
                    }
                    else
                    {
                        objectsList = IsTreeEnabled ? ProjectLink.RepositoryLink.GetObjectsDescriptors((lookNode.Tag as IMetadataObjectDescriptor).Id, showKind) : ProjectLink.RepositoryLink.GetObjectsDescriptors(showKind);
                    }
                    foreach (IMetadataObjectDescriptor desc in objectsList)
                    {
                        if ((showKind != MetadataObjectKind.Folder) && (desc.Kind == MetadataObjectKind.Folder))
                            continue;//папки уже вывели на предыдущем проходе цикла While, пропускаем
                        string desclabel = desc.Label;
                        switch (desc.Kind)
                        {
                            case MetadataObjectKind.Indicator:                                                                
                                if (!Indicator.IsUserType((IndicatorType)desc.Subkind)) //непользовательские показатели не выводим
                                {
                                    continue;
                                }
                                IIndicator ind = desc.Bind() as IIndicator;//отстойно что биндю, это лишние тормоза, но иначе не придумал как                                
                                if (ind.GetIndicatorLimiterState() != IndicatorLimiterState.Indicator)
                                    continue; //ограничители значений не выводим
                                break;
                            case MetadataObjectKind.Table:
                                if (desclabel == Repository.WorldsTableLabel) //таблицу миров не выводим
                                {
                                    continue;
                                }
                                break;
                            case MetadataObjectKind.Dimension:
                                if (desclabel == ProjectLink.RepositoryLink.WorldsDimension.Label) //не выводим измерение миров
                                {
                                    continue;
                                }
                                break;
                        }
                        ListViewItem item = items.Add(desc.Name,
                            desc.Kind.GetImageKey(
                            (ObjectsList.View == View.LargeIcon) ? MetadataObjectImageSize.Large :
                            MetadataObjectImageSize.Small, MetadataObjectState.Normal));
                        item.SubItems.Add(desc.Label);
                        item.SubItems.Add(desc.Description);
                        item.SubItems.Add(desc.Kind.ToUserString());//полный вид не вывести (через IMetadataObject.KindToUserString), т.к. потребуется бинд, а это тормоза
                        item.Tag = desc;
                        if (_cuttedItemsDescriptors.Contains(desc))
                        {
                            item.ForeColor = SystemColors.GrayText;
                        }
                        if (_beforeSelectedObjectsIds.Contains(desc.Id))
                        {
                            _programFocusChange = true;
                            item.Selected = true;
                            _programFocusChange = false;
                        }
                    }
                    if (showKind == MetadataObjectKind.Folder)
                    {
                        showKind = VisibleTypes.Kind;
                        continue;
                    }
                    break;
                }
                break;
            }
            ObjectsList.EndUpdate();
        }

        /// <summary>
        /// Отображение диалога "О программе..."
        /// </summary>
        public void ShowAboutDialog()
        {
            _aboutProgramDialog.ShowDialog();
        }

        /// <summary>
        /// Возвращает/устанавливает тип отображаемых объектов
        /// </summary>
        public MetadataObjectsVisibleTypes VisibleTypes
        {
            get
            {
                return _visibleTypes;
            }
            set
            {
                _visibleTypes = value;
                int needIndex = (int)(_visibleTypes.Kind) - 2; //-2, потому что None и Folders не выводим                
                if (ObjectKindsView.SelectedItems[0].Index != needIndex)
                {                    
                    if (_visibleTypes.All)
                    {
                        //if (ObjectKindsView.SelectedItems[0].Group.Name == "AllKinds")
                        {
                            needIndex = ObjectKindsView.Items[ObjectKindsView.Items.Count - 1].Index;
                            if (needIndex == ObjectKindsView.SelectedItems[0].Index)
                            {                                
                                RefreshObjects();
                                return;
                            }
                        }
                    }
                    _programKindChange = true;
                    ObjectKindsView.SelectedItems[0].Focused = false;
                    ObjectKindsView.SelectedItems[0].Selected = false;
                    ObjectKindsView.Items[needIndex].Focused = true;
                    _programKindChange = false;
                    ObjectKindsView.Items[needIndex].Selected = true;                    
                }
                else
                {
                    RefreshObjects();
                }
            }
        }

        /// <summary>
        /// Отображает диалог редактирования поля таблицы
        /// </summary>
        private void ShowEditFieldDialog()
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ITable tab = itemDescriptor.Bind() as ITable;
            DataGridViewRow row = _grdFields.SelectedRows[0];
            int memindex = row.Index;
            FieldPropertiesDialog efed = new FieldPropertiesDialog(_MainFormLink, false, tab, row.Cells["nameColumn"].Value as string);
            efed.ShowDialog();
            UpdateObjectProperties();
            _grdFields.Rows[memindex].Selected = true;
        }

        /// <summary>
        /// Обрабатывает выбор пункта "Редактировать поле" в тулбаре грида полей пользовательских таблиц
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ChangePropertiesOfSelectedField(object sender, EventArgs args)
        {
            ShowEditFieldDialog();
        }

        /// <summary>
        /// Обрабатывает выбор пункта "Удалить поле" в тулбаре грида полей пользовательских таблиц
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void DeleteSelectedField(object sender, EventArgs args)
        {
            if (GeneralMethods.ShowWarning(Resources.BI_PROJECTEXPLORER_TABLE_DELETINGALERT, MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
                ITable tab = itemDescriptor.Bind() as ITable;
                DataGridViewRow row = _grdFields.SelectedRows[0];
                string cname = row.Cells["nameColumn"].Value as string;
                if (_projectLink.IsTableColumnUsed(tab.Label, cname))
                {
                    GeneralMethods.ShowUserError(Resources.BI_PROJECTEXPLORER_TABLE_ERROR_TABLECOLUMNUSED);
                }
                else
                {
                    if (!tab.IsPrimaryField(cname))
                    {
                        tab.DeleteColumn(cname);
                        UpdateObjectProperties();
                    }
                    else
                    {
                        GeneralMethods.ShowUserError(Resources.BI_PROJECTEXPLORER_TABLE_ERROR_DELETEINGKEYCOLUMN);
                    }
                }
            }
        }

        /// <summary>
        /// Добавляет новое поле в таблицу
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void AddFieldToUserTable(object sender, EventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ITable tab = itemDescriptor.Bind() as ITable;
            FieldPropertiesDialog nfd = new FieldPropertiesDialog(_MainFormLink, true, tab, string.Empty);
            nfd.ShowDialog();
            UpdateObjectProperties();
            _grdFields.Rows[_grdFields.Rows.Count - 1].Selected = true;
        }

        /// <summary>
        /// Обрабатывает даблклик по полю в гриде полей пользовательских таблиц
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void DoubleClickFieldsGrid(object sender, DataGridViewCellEventArgs args)
        {
            if (args.RowIndex != -1)
            {
                ShowEditFieldDialog();
            }
        }

        /// <summary>
        /// Изменяет первичный ключ таблицы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ChangePrimaryKey(object sender, EventArgs args)
        {
            _grdFields.EndEdit();
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ITable tab = itemDescriptor.Bind() as ITable;
            List<string> cols = new List<string>();
            int c = _grdFields.Rows.Count;
            for (int i = 0; i < c; i++)
            {
                DataGridViewRow row = _grdFields.Rows[i];
                if ((bool)(row.Cells["keyColumn"].Value))
                {
                    cols.Add(row.Cells["nameColumn"].Value as string);
                }
            }
            try
            {
                tab.SetPrimaryFields(cols);
            }
            catch (BITablePrimaryException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                UpdateObjectProperties();
            }
        }

        /// <summary>
        /// Обрабатывает смену отметки в гриде полей пользователских таблиц
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void FieldSelectionChanged(object sender, EventArgs args)
        {
            bool isAnySelected = _grdFields.SelectedRows.Count == 1;
            _toolFields.Items["editFieldButton"].Enabled = isAnySelected;
            _toolFields.Items["deleteFieldButton"].Enabled = isAnySelected;
        }

        /// <summary>
        /// Создает элементы управления структурой пользовательской таблицы
        /// </summary>
        private void PutStructureControlsForTable()
        {            
            _toolFields = new ToolStrip();
            _toolFields.Parent = ObjectStructureArea;
            _toolFields.Dock = DockStyle.Top;
            _toolFields.Items.Add(Resources.BI_PROJECTEXPLORER_TABLE_ADDFIELD_CAPTION, SoftwareConsulting.BI11.Studio.UI.Properties.Resources.plus, AddFieldToUserTable);
            _toolFields.Items[_toolFields.Items.Count - 1].Name = "addFieldButton";
            _toolFields.Items["addFieldButton"].DisplayStyle = ToolStripItemDisplayStyle.Image;
            _toolFields.Items["addFieldButton"].ImageTransparentColor = Color.Magenta;
            _toolFields.Items.Add(Resources.BI_PROJECTEXPLORER_TABLE_EDITFIELD_CAPTION, SoftwareConsulting.BI11.Studio.UI.Properties.Resources.Edit, ChangePropertiesOfSelectedField);
            _toolFields.Items[_toolFields.Items.Count - 1].Name = "editFieldButton";
            _toolFields.Items["editFieldButton"].DisplayStyle = ToolStripItemDisplayStyle.Image;
            _toolFields.Items["editFieldButton"].ImageTransparentColor = Color.Magenta;
            _toolFields.Items["editFieldButton"].Enabled = false;
            _toolFields.Items.Add(Resources.BI_PROJECTEXPLORER_TABLE_DELETEFIELD_CAPTION, SoftwareConsulting.BI11.Studio.UI.Properties.Resources.delete, DeleteSelectedField);
            _toolFields.Items[_toolFields.Items.Count - 1].Name = "deleteFieldButton";
            _toolFields.Items["deleteFieldButton"].DisplayStyle = ToolStripItemDisplayStyle.Image;
            _toolFields.Items["deleteFieldButton"].ImageTransparentColor = Color.Magenta;
            _toolFields.Items["deleteFieldButton"].Enabled = false;
            _toolFields.Items.Add(Resources.BI_PROJECTEXPLORER_TABLE_KEYFIELD_CAPTION, SoftwareConsulting.BI11.Studio.UI.Properties.Resources.primarykey, ChangePrimaryKey);
            _toolFields.Items[_toolFields.Items.Count - 1].Name = "keyButton";
            _toolFields.Items["keyButton"].DisplayStyle = ToolStripItemDisplayStyle.Image;
            _toolFields.Items["keyButton"].ImageTransparentColor = Color.Magenta;
            _toolFields.Items["keyButton"].Enabled = true;
            Panel labelPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label fieldsLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_TABLE_FIELDS_CAPTION,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = labelPanel,
                Dock = DockStyle.Top
            };
            labelPanel.Height = fieldsLabel.Height;
            labelPanel.Parent = ObjectStructureArea;
            labelPanel.Top = _toolFields.Height;
            labelPanel.Left = 0;
            labelPanel.Width = ObjectStructureArea.Width;
            labelPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _grdFields = new DataGridView();
            _grdFields.MultiSelect = false;
            _grdFields.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            _grdFields.AllowUserToOrderColumns = true;
            _grdFields.ShowEditingIcon = false;
            _grdFields.ShowRowErrors = false;
            _grdFields.RowHeadersVisible = false;
            _grdFields.ColumnHeadersVisible = true;
            _grdFields.AllowUserToAddRows = false;
            _grdFields.AllowUserToDeleteRows = false;
            DataGridViewCheckBoxColumn keyColumn = new DataGridViewCheckBoxColumn()
            {
                HeaderText = Resources.BI_PROJECTEXPLORER_TABLE_FIELDS_KEY,
                Name = "keyColumn",
                ReadOnly = false,
                Resizable = DataGridViewTriState.True,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader
            };
            _grdFields.Columns.Add(keyColumn);
            _grdFields.Columns.Add("nameColumn", Resources.BI_PROJECTEXPLORER_TABLE_FIELDS_NAME);
            _grdFields.Columns.Add("typeColumn", Resources.BI_PROJECTEXPLORER_TABLE_FIELDS_TYPE);
            _grdFields.Columns["nameColumn"].ReadOnly = true;
            _grdFields.Columns["nameColumn"].Resizable = DataGridViewTriState.True;
            _grdFields.Columns["nameColumn"].ValueType = Type.GetType("System.String");
            _grdFields.Columns["nameColumn"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            _grdFields.Columns["typeColumn"].ReadOnly = true;
            _grdFields.Columns["typeColumn"].Resizable = DataGridViewTriState.True;
            _grdFields.Columns["typeColumn"].ValueType = Type.GetType("System.String");
            _grdFields.Columns["typeColumn"].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            _grdFields.CellDoubleClick += DoubleClickFieldsGrid;
            _grdFields.SelectionChanged += FieldSelectionChanged;
            _grdFields.Parent = ObjectStructureArea;
            _grdFields.Top = labelPanel.Top + labelPanel.Height;
            _grdFields.Left = 0;
            _grdFields.Width = ObjectStructureArea.Width;
            _grdFields.Height = ObjectStructureArea.Height - labelPanel.Height - _toolFields.Height;
            _grdFields.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ITable tab = itemDescriptor.Bind() as ITable;
            ICollection<string> cnames = tab.GetColumnNames();
            foreach (string cname in cnames)
            {
                _grdFields.Rows.Add();
                int i = _grdFields.Rows.Count - 1;
                // установление полей первичного ключа                
                _grdFields.Rows[i].Cells["nameColumn"].Value = cname;
                _grdFields.Rows[i].Cells["typeColumn"].Value = tab.GetColumnProperties(cname).ColumnType.ToString();
                _grdFields.Rows[i].Cells["keyColumn"].Value = tab.IsPrimaryField(cname);
            }
            if (_grdFields.Rows.Count > 0)
                _grdFields.Rows[0].Selected = true;
        }

        /// <summary>
        /// Обновляет возможность применения изменений в привязке таблиц измерения
        /// </summary>
        private bool UpdateBindDimensionAbilities()
        {
            bool nonull = _grdFields.Rows[0].Cells["tabColumn"].Value as string != Constants.NullDoesNotMatterString;
            nonull = nonull && _grdFields.Rows[1].Cells["tabColumn"].Value as string != Constants.NullDoesNotMatterString;
            _toolFields.Items["bindDimensionButton"].Enabled = nonull;
            return nonull;
        }

        /// <summary>
        /// Обрабатывает смену таблицы в гриде привязок измерения
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ChangeTableInGrid(object sender, DataGridViewCellEventArgs args)
        {
            if (args.ColumnIndex == _grdFields.Columns["tabColumn"].Index)
            {
                DataGridViewComboBoxCell combocell = _grdFields.Rows[args.RowIndex].Cells["tabfieldColumn"] as DataGridViewComboBoxCell;
                combocell.Value = null;
                combocell.Items.Clear();
                string newtablabel = (_grdFields.Rows[args.RowIndex].Cells[args.ColumnIndex] as DataGridViewComboBoxCell).Value as string;
                if (newtablabel == Constants.NullDoesNotMatterString)
                {
                    combocell.Items.Add(Constants.NullDoesNotMatterString);
                }
                else
                {
                    ITable tab = ProjectLink.RepositoryLink.GetObjectDescriptorByLabel(newtablabel, MetadataObjectKind.Table).Bind() as ITable;
                    combocell.Items.AddRange(tab.GetColumnNames().ToArray());
                }
                combocell.Value = combocell.Items[0];
                UpdateBindDimensionAbilities();
            }
        }

        /// <summary>
        /// Осуществляет привязку измерения к пользовательским таблицам
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void BindDimension(object sender, EventArgs args)
        {
            _grdFields.EndEdit();
            if (UpdateBindDimensionAbilities())
            {
                IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
                IFactsDimension fdim = itemDescriptor.Bind() as IFactsDimension;
                string usingCubeObjectsString = string.Empty;
                var usings = new List<IMetadataObjectDescriptor>();
                foreach (IMetadataObjectDescriptor desc in ProjectLink.RepositoryLink.WalkObjects(MetadataObjectKind.Cube, MetadataObjectKind.TimeSeries))                
                {
                    foreach (IMetadataObjectDescriptor desc2 in desc.Bind().WalkNecessaryObjects())
                    {
                        if (desc.Id == desc2.Id)
                        {
                            usings.Add(desc);
                            usingCubeObjectsString = usingCubeObjectsString + desc.ToString() + ", ";
                            break;
                        }
                    }                    
                }                
                if (!string.IsNullOrEmpty(usingCubeObjectsString))
                {
                    usingCubeObjectsString = usingCubeObjectsString.Substring(0, usingCubeObjectsString.Length - 2);
                    if (GeneralMethods.ShowWarning(Resources.BI_PROJECTEXPLORER_DIMENSIONUSED + usingCubeObjectsString, MessageBoxButtons.YesNo) != DialogResult.Yes)
                    {
                        return;
                    }
                    foreach (IMetadataObjectDescriptor desc in usings)
                    {
                        if (desc.Kind == MetadataObjectKind.TimeSeries)
                            continue; //по идее все равно никогда сюда не попадет, т.к. привязка может меняться только для измерений фактов, но на всякий случай...
                        IDateAndFactCorrelations dafc = desc.Bind() as IDateAndFactCorrelations;
                        dafc.ClearValues();
                    }
                }
                ITableField utfk = new TableField(_projectLink.RepositoryLink.GetObjectDescriptorByLabel(_grdFields.Rows[0].Cells["tabColumn"].Value as string, MetadataObjectKind.Table).Id, _grdFields.Rows[0].Cells["tabfieldColumn"].Value as string);
                ITableField utfn = new TableField(_projectLink.RepositoryLink.GetObjectDescriptorByLabel(_grdFields.Rows[1].Cells["tabColumn"].Value as string, MetadataObjectKind.Table).Id, _grdFields.Rows[1].Cells["tabfieldColumn"].Value as string);
                ITableField utfp = (_grdFields.Rows[2].Cells["tabColumn"].Value as string) == Constants.NullDoesNotMatterString ?
                    null :
                    new TableField(_projectLink.RepositoryLink.GetObjectDescriptorByLabel(_grdFields.Rows[2].Cells["tabColumn"].Value as string, MetadataObjectKind.Table).Id, _grdFields.Rows[2].Cells["tabfieldColumn"].Value as string);                
                try
                {
                    fdim.BindToDimensionTables(utfk, utfn, utfp);
                }
                catch (BIDimensionCantBindException ex)
                {
#if DEBUG
                    GeneralMethods.ShowUserError(ex.Message + char.ConvertFromUtf32(10) + char.ConvertFromUtf32(13) + ex.StackTrace);
#else
                GeneralMethods.ShowUserError(ex.Message);
#endif
                }
            }
        }

        /// <summary>
        /// Обрабатывает нажатие кнопок в гриде измерений куба
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ProcessCubeDimensionsChange(object sender, DataGridViewCellEventArgs args)
        {
            if (args.RowIndex >= 0)
            {
                string dimlabel = _grdFields.Rows[args.RowIndex].Cells["dimColumn"].Value as string;
                IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
                ICube cube = itemDescriptor.Bind() as ICube;
                IDimension dim = ProjectLink.RepositoryLink.GetObjectDescriptorByLabel(dimlabel, MetadataObjectKind.Dimension).Bind() as IDimension;
                bool ok = true;
                if (args.ColumnIndex == _grdFields.Columns["delColumn"].Index)
                {
                    //удаление измерения                    
                    try
                    {
                        cube.RemoveDimension(dim);
                    }
                    catch (BICubeWorldsDimBlockedException ex)
                    {
                        GeneralMethods.ShowUserError(ex.Message);
                        ok = false;
                    }
                }
                if (args.ColumnIndex == _grdFields.Columns["upColumn"].Index)
                {
                    if ((cube.GetFactsDimensionByPosition(0).Label != dimlabel)
                        &&
                        ((cube.GetCalendarDimension() == null) || (cube.GetCalendarDimension().Label != dimlabel)))
                    {
                        cube.UpFactsDimension(dim as IFactsDimension);
                    }
                    else
                    {
                        ok = false;
                    }
                }
                if (args.ColumnIndex == _grdFields.Columns["downColumn"].Index)
                {
                    if ((cube.GetFactsDimensionByPosition(cube.GetFactsDimensionsCount() - 1).Label != dimlabel)
                        &&
                        ((cube.GetCalendarDimension() == null) || (cube.GetCalendarDimension().Id != dim.Id)))
                    {
                        cube.DownFactsDimension(dim as IFactsDimension);
                    }
                    else
                    {
                        ok = false;
                    }
                }
                if (ok)
                {
                    UpdateObjectProperties();
                }
            }
        }

        /// <summary>
        /// Добавляет измерение в куб
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void AddDimensionToCube(object sender, EventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICube cube = itemDescriptor.Bind() as ICube;
            string dimlabel = (_toolFields.Items["newDimensionNameBox"] as ToolStripComboBox).SelectedItem as string;
            IDimension dim = ProjectLink.RepositoryLink.GetObjectDescriptorByLabel(dimlabel, MetadataObjectKind.Dimension).Bind() as IDimension;
            cube.AddDimension(dim);
            UpdateObjectProperties();
        }

        /// <summary>
        /// Добавляет модель в расчет
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void AddModelToCalculation(object sender, EventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalculation calc = itemDescriptor.Bind() as ICalculation;
            string modellabel = (_modelsTools.Items["newModelNameBox"] as ToolStripComboBox).SelectedItem as string;
            IModel model = ProjectLink.RepositoryLink.GetObjectDescriptorByLabel(modellabel, MetadataObjectKind.Model).Bind() as IModel;
            calc.AddModel(model);
            UpdateObjectProperties();
        }

        /// <summary>
        /// Создает элементы управления структурой куба
        /// </summary>
        private void PutStructureControlsForCube()
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICube cube = itemDescriptor.Bind() as ICube;
            _toolFields = new ToolStrip();
            _toolFields.Parent = ObjectStructureArea;
            _toolFields.Dock = DockStyle.Top;
            ToolStripComboBox tsi = new ToolStripComboBox("newDimensionNameBox")
            {
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            ComboBox.ObjectCollection items = tsi.Items;
            items.Clear();
            foreach (MetadataObjectDescriptor info in ProjectLink.RepositoryLink.GetObjectsDescriptors(MetadataObjectKind.Dimension))
            {                
                if (((DimensionKind)info.Subkind == DimensionKind.Calendar) && (cube.GetCalendarDimension() == null))
                {
                    items.Add(info.Label);
                }
                if (((DimensionKind)info.Subkind == DimensionKind.Facts) && (!cube.IsFactsDimensionUsed(info.Id)))
                {
                    items.Add(info.Label);
                }
            }
            if (tsi.Items.Count > 0)
            {
                tsi.SelectedIndex = 0;
            }
            _toolFields.Items.Add(tsi);
            _toolFields.Items.Add(Resources.BI_PROJECTEXPLORER_CUBE_ADDDIMENSION_CAPTION, SoftwareConsulting.BI11.Studio.UI.Properties.Resources.plus, AddDimensionToCube);
            _toolFields.Items[_toolFields.Items.Count - 1].Name = "addDimensionButton";
            _toolFields.Items["addDimensionButton"].DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
            _toolFields.Items["addDimensionButton"].TextImageRelation = TextImageRelation.ImageBeforeText;
            _toolFields.Items["addDimensionButton"].ImageTransparentColor = Color.Magenta;
            _toolFields.Items["addDimensionButton"].Enabled = tsi.Items.Count > 0;
            Panel labelPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label fieldsLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CUBE_DIMENSIONS_CAPTION,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = labelPanel,
                Dock = DockStyle.Top
            };
            labelPanel.Height = fieldsLabel.Height;
            labelPanel.Parent = ObjectStructureArea;
            labelPanel.Top = _toolFields.Height;
            labelPanel.Left = 0;
            labelPanel.Width = ObjectStructureArea.Width;
            labelPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _grdFields = new DataGridView();
            _grdFields.MultiSelect = false;
            _grdFields.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            _grdFields.AllowUserToOrderColumns = true;
            _grdFields.ShowEditingIcon = false;
            _grdFields.ShowRowErrors = false;
            _grdFields.RowHeadersVisible = false;
            _grdFields.ColumnHeadersVisible = true;
            _grdFields.AllowUserToAddRows = false;
            _grdFields.AllowUserToDeleteRows = false;
            DataGridViewTextBoxColumn dimColumn = new DataGridViewTextBoxColumn()
            {
                HeaderText = Resources.BI_PROJECTEXPLORER_CUBE_FIELDS_DIMENSION,
                Name = "dimColumn",
                ReadOnly = true,
                Resizable = DataGridViewTriState.True,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            };
            _grdFields.Columns.Add(dimColumn);
            DataGridViewButtonColumn delColumn = new DataGridViewButtonColumn()
            {
                HeaderText = string.Empty,
                Name = "delColumn",
                ReadOnly = false,
                Resizable = DataGridViewTriState.False,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            };
            _grdFields.Columns.Add(delColumn);
            DataGridViewButtonColumn upColumn = new DataGridViewButtonColumn()
            {
                HeaderText = string.Empty,
                Name = "upColumn",
                ReadOnly = false,
                Resizable = DataGridViewTriState.False,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            };
            _grdFields.Columns.Add(upColumn);
            DataGridViewButtonColumn downColumn = new DataGridViewButtonColumn()
            {
                HeaderText = string.Empty,
                Name = "downColumn",
                ReadOnly = false,
                Resizable = DataGridViewTriState.False,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            };
            _grdFields.Columns.Add(downColumn);
            _grdFields.CellContentClick += ProcessCubeDimensionsChange;
            _grdFields.Parent = ObjectStructureArea;
            _grdFields.Top = labelPanel.Top + labelPanel.Height;
            _grdFields.Left = 0;
            _grdFields.Width = ObjectStructureArea.Width;
            _grdFields.Height = ObjectStructureArea.Height - labelPanel.Height - _toolFields.Height;
            _grdFields.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
            /*List<string> allDimsLabels = new List<string>();            
            int c = cube.FactsDimensionsCount;
            for (int i = 0; i < c; i++)            
            {
                allDimsLabels.Add(cube.GetFactsDimensionByPosition(i).label);
            } */
            ICalendarDimension cdim = cube.GetCalendarDimension();
            if (cdim != null)
            {
                _grdFields.Rows.Add();
                DataGridViewRow row = _grdFields.Rows[_grdFields.Rows.Count - 1];
                row.Cells["dimColumn"].Value = cdim.Label;
                DataGridViewButtonCell buttoncell = row.Cells["delColumn"] as DataGridViewButtonCell;
                buttoncell.Value = Resources.BI_PROJECTEXPLORER_CUBE_REMOVEDIMENSION_CAPTION;
                buttoncell = row.Cells["upColumn"] as DataGridViewButtonCell;
                buttoncell.Value = string.Empty;
                buttoncell.ReadOnly = true;
                buttoncell = row.Cells["downColumn"] as DataGridViewButtonCell;
                buttoncell.Value = string.Empty;
                buttoncell.ReadOnly = true;
            }
            int c = cube.GetFactsDimensionsCount();
            for (int i = 0; i < c; i++)
            {
                string dimlabel = cube.GetFactsDimensionByPosition(i).Label;
                _grdFields.Rows.Add();
                DataGridViewRow row = _grdFields.Rows[_grdFields.Rows.Count - 1];
                row.Cells["dimColumn"].Value = dimlabel.ToString();
                DataGridViewButtonCell buttoncell = row.Cells["delColumn"] as DataGridViewButtonCell;
                buttoncell.Value = Resources.BI_PROJECTEXPLORER_CUBE_REMOVEDIMENSION_CAPTION;
                buttoncell = row.Cells["upColumn"] as DataGridViewButtonCell;
                if (i > 0)
                {
                    buttoncell.Value = "^";
                }
                buttoncell = row.Cells["downColumn"] as DataGridViewButtonCell;
                if (i < c - 1)
                {
                    buttoncell.Value = "v";
                }
            }
        }

        /// <summary>
        /// Создает элементы управления структурой измерения фактов
        /// </summary>
        private void PutStructureControlsForFactsDimension()
        {
            _toolFields = new ToolStrip();
            _toolFields.Parent = ObjectStructureArea;
            _toolFields.Dock = DockStyle.Top;
            _toolFields.Items.Add(Resources.BI_PROJECTEXPLORER_DIMENSION_APPLY, SoftwareConsulting.BI11.Studio.UI.Properties.Resources.apply, BindDimension);
            _toolFields.Items[_toolFields.Items.Count - 1].Name = "bindDimensionButton";
            _toolFields.Items["bindDimensionButton"].DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
            _toolFields.Items["bindDimensionButton"].TextImageRelation = TextImageRelation.ImageBeforeText;
            _toolFields.Items["bindDimensionButton"].ImageTransparentColor = Color.Magenta;
            _toolFields.Items["bindDimensionButton"].Enabled = false;
            Panel labelPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label bindsLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_DIMENSION_BINDINGS,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = labelPanel,
                Dock = DockStyle.Top
            };
            labelPanel.Height = bindsLabel.Height;
            labelPanel.Parent = ObjectStructureArea;
            labelPanel.Top = _toolFields.Height;
            labelPanel.Left = 0;
            labelPanel.Width = ObjectStructureArea.Width;
            labelPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _grdFields = new DataGridView();
            _grdFields.MultiSelect = false;
            _grdFields.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            _grdFields.AllowUserToOrderColumns = false;
            _grdFields.ShowEditingIcon = false;
            _grdFields.ShowRowErrors = false;
            _grdFields.RowHeadersVisible = false;
            _grdFields.ColumnHeadersVisible = true;
            _grdFields.AllowUserToAddRows = false;
            _grdFields.AllowUserToDeleteRows = false;
            DataGridViewTextBoxColumn fieldColumn = new DataGridViewTextBoxColumn()
            {
                HeaderText = Resources.BI_PROJECTEXPLORER_DIMENSION_COLUMNS_FIELDNAME,
                Name = "fieldColumn",
                ReadOnly = true,
                Resizable = DataGridViewTriState.True,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            };
            _grdFields.Columns.Add(fieldColumn);
            DataGridViewComboBoxColumn tabColumn = new DataGridViewComboBoxColumn()
            {
                HeaderText = Resources.BI_PROJECTEXPLORER_DIMENSION_COLUMNS_TABLELABEL,
                Name = "tabColumn",
                ReadOnly = false,
                Resizable = DataGridViewTriState.True,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
                DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton
            };
            _grdFields.Columns.Add(tabColumn);
            DataGridViewComboBoxColumn tabfieldColumn = new DataGridViewComboBoxColumn()
            {
                HeaderText = Resources.BI_PROJECTEXPLORER_DIMENSION_COLUMNS_TABLEFIELD,
                Name = "tabfieldColumn",
                ReadOnly = false,
                Resizable = DataGridViewTriState.True,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells,
                DisplayStyle = DataGridViewComboBoxDisplayStyle.DropDownButton
            };
            _grdFields.Columns.Add(tabfieldColumn);
            _grdFields.EditMode = DataGridViewEditMode.EditOnEnter;
            _grdFields.CellEndEdit += ChangeTableInGrid;
            _grdFields.Parent = ObjectStructureArea;
            _grdFields.Top = labelPanel.Top + labelPanel.Height;
            _grdFields.Left = 0;
            _grdFields.Width = ObjectStructureArea.Width;
            _grdFields.Height = ObjectStructureArea.Height - labelPanel.Height - _toolFields.Height;
            _grdFields.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
            List<IMetadataObjectDescriptor> allTabsDescs = new List<IMetadataObjectDescriptor>();            
            foreach (IMetadataObjectDescriptor desc in ProjectLink.RepositoryLink.GetObjectsDescriptors(MetadataObjectKind.Table))
            {
                ITable cTab = desc.Bind() as ITable;                
                if (cTab.GetColumnNames().Count > 0)
                {                    
                    allTabsDescs.Add(desc);
                }
            }
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            IFactsDimension fdim = itemDescriptor.Bind() as IFactsDimension;

            _grdFields.Rows.Add();
            DataGridViewRow row = _grdFields.Rows[_grdFields.Rows.Count - 1];
            row.Cells["fieldColumn"].Value = Resources.BI_PROJECTEXPLORER_DIMENSION_ROWS_KEY;
            DataGridViewComboBoxCell combocell = row.Cells["tabColumn"] as DataGridViewComboBoxCell;
            TableField utf = fdim.GetFieldOfParentTableByConnectedDimensionField(DimensionTableField.Key);
            combocell.Items.Add(Constants.NullDoesNotMatterString);
            foreach (MetadataObjectDescriptor info in allTabsDescs)
            {
                combocell.Items.Add(info.Label);
            }
            if (utf != null)
            {
                combocell.Value = _projectLink.RepositoryLink.GetObjectDescriptorById(utf.TableId).Label;
                combocell = row.Cells["tabfieldColumn"] as DataGridViewComboBoxCell;
                ITable tab = ProjectLink.RepositoryLink.GetObjectDescriptorById(utf.TableId).Bind() as ITable;
                combocell.Items.AddRange(tab.GetColumnNames().ToArray());
                combocell.Value = utf.FieldName;
            }
            else
            {
                combocell.Value = Constants.NullDoesNotMatterString;
                combocell = row.Cells["tabfieldColumn"] as DataGridViewComboBoxCell;
                combocell.Items.Add(Constants.NullDoesNotMatterString);
                combocell.Value = Constants.NullDoesNotMatterString;
            }

            _grdFields.Rows.Add();
            row = _grdFields.Rows[_grdFields.Rows.Count - 1];
            row.Cells["fieldColumn"].Value = Resources.BI_PROJECTEXPLORER_DIMENSION_ROWS_NAME;
            combocell = row.Cells["tabColumn"] as DataGridViewComboBoxCell;
            utf = fdim.GetFieldOfParentTableByConnectedDimensionField(DimensionTableField.Name);
            combocell.Items.Add(Constants.NullDoesNotMatterString);
            foreach (MetadataObjectDescriptor info in allTabsDescs)
            {
                combocell.Items.Add(info.Label);
            }
            if (utf != null)
            {
                combocell.Value = _projectLink.RepositoryLink.GetObjectDescriptorById(utf.TableId).Label;
                combocell = row.Cells["tabfieldColumn"] as DataGridViewComboBoxCell;
                ITable tab = ProjectLink.RepositoryLink.GetObjectDescriptorById(utf.TableId).Bind() as ITable;
                combocell.Items.AddRange(tab.GetColumnNames().ToArray());
                combocell.Value = utf.FieldName;
            }
            else
            {
                combocell.Value = Constants.NullDoesNotMatterString;
                combocell = row.Cells["tabfieldColumn"] as DataGridViewComboBoxCell;
                combocell.Items.Add(Constants.NullDoesNotMatterString);
                combocell.Value = Constants.NullDoesNotMatterString;
            }

            _grdFields.Rows.Add();
            row = _grdFields.Rows[_grdFields.Rows.Count - 1];
            row.Cells["fieldColumn"].Value = Resources.BI_PROJECTEXPLORER_DIMENSION_ROWS_PARENTKEY;
            combocell = row.Cells["tabColumn"] as DataGridViewComboBoxCell;
            utf = fdim.GetFieldOfParentTableByConnectedDimensionField(DimensionTableField.ParentKey);
            combocell.Items.Add(Constants.NullDoesNotMatterString);
            foreach (MetadataObjectDescriptor info in allTabsDescs)
            {
                combocell.Items.Add(info.Label);
            }
            if (utf != null)
            {
                combocell.Value = _projectLink.RepositoryLink.GetObjectDescriptorById(utf.TableId).Label;
                combocell = row.Cells["tabfieldColumn"] as DataGridViewComboBoxCell;
                ITable tab = ProjectLink.RepositoryLink.GetObjectDescriptorById(utf.TableId).Bind() as ITable;
                combocell.Items.AddRange(tab.GetColumnNames().ToArray());
                combocell.Value = utf.FieldName;
            }
            else
            {
                combocell.Value = Constants.NullDoesNotMatterString;
                combocell = row.Cells["tabfieldColumn"] as DataGridViewComboBoxCell;
                combocell.Items.Add(Constants.NullDoesNotMatterString);
                combocell.Value = Constants.NullDoesNotMatterString;
            }
        }

        /// <summary>
        /// Обновляет формат бокса выбора даты в соответсвии с выбранной динамикой
        /// </summary>
        /// <param name="picker"></param>
        /// <param name="dyn"></param>
        private void UpdateDateTimePickerFormat(DateTimePicker picker, CalendarDynamics dyn)
        {
            switch (dyn)
            {
                case CalendarDynamics.None:
                    Assert.Fail(Assert.Id.Assert00124);
                    break;
                case CalendarDynamics.Years:
                    picker.Format = DateTimePickerFormat.Custom;
                    picker.CustomFormat = "yyyy";
                    break;
                case CalendarDynamics.YearsMonths:
                    picker.Format = DateTimePickerFormat.Custom;
                    picker.CustomFormat = CultureInfo.CurrentUICulture.DateTimeFormat.YearMonthPattern;
                    break;
                case CalendarDynamics.MonthsDays:
                    picker.Format = DateTimePickerFormat.Long;
                    break;
            }
        }

        /// <summary>
        /// Обрабатывает смену динамики в календарном измерении
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void dynBox_SelectedIndexChanged(object sender, EventArgs args)
        {
            IMetadataObjectDescriptor itemInfo = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalendarDimension cdim = ProjectLink.RepositoryLink.GetObjectDescriptorById(itemInfo.Id) as ICalendarDimension;
            string usingDAFCObjectsString = string.Empty;
            var usings = new List<IMetadataObjectDescriptor>();            
            foreach (MetadataObjectDescriptor desc in ProjectLink.RepositoryLink.WalkObjects(MetadataObjectKind.Cube, MetadataObjectKind.TimeSeries))
            {
                foreach (MetadataObjectDescriptor desc2 in desc.Bind().WalkNecessaryObjects())
                {
                    if (desc.Id == desc2.Id)
                    {
                        usings.Add(desc);
                        usingDAFCObjectsString = usingDAFCObjectsString + desc.ToString() + ", ";
                        break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(usingDAFCObjectsString))
            {
                usingDAFCObjectsString = usingDAFCObjectsString.Substring(0, usingDAFCObjectsString.Length - 2);
                if (GeneralMethods.ShowWarning(Resources.BI_PROJECTEXPLORER_CALENDARDIMENSION_USED_QUESTION + usingDAFCObjectsString, MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    return;
                }                
            }
            cdim.SetDynamics((CalendarDynamics)_dynBox.SelectedIndex + 1);
            foreach (IMetadataObjectDescriptor desc in usings)
            {
                IDateAndFactCorrelations dafc = desc.Bind() as IDateAndFactCorrelations;                
                dafc.ClearValuesOutOfDate();
            }
            UpdateDateTimePickerFormat(_fromDateBox, cdim.GetDynamics());
            UpdateDateTimePickerFormat(_tillDateBox, cdim.GetDynamics());
        }

        /// <summary>
        /// Обрабатывает смену динамики в модели
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void modeldynBox_SelectedIndexChanged(object sender, EventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            IModel model = itemDescriptor.Bind() as IModel;
            model.SetDynamics((CalendarDynamics)_dynBox.SelectedIndex + 1);
            UpdateDateTimePickerFormat(_identfromBox, model.GetDynamics());
            UpdateDateTimePickerFormat(_identtillBox, model.GetDynamics());
            UpdateDateTimePickerFormat(_forefromBox, model.GetDynamics());
            UpdateDateTimePickerFormat(_foretillBox, model.GetDynamics());
        }

        /// <summary>
        /// Обрабатывает смену начальной точки календарного измерения
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void fromBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalendarDimension cdim = itemDescriptor.Bind() as ICalendarDimension;
            string usingDAFCObjectsString = string.Empty;
            var usings = new List<IMetadataObjectDescriptor>();            
            foreach (IMetadataObjectDescriptor desc in ProjectLink.RepositoryLink.WalkObjects(MetadataObjectKind.Cube, MetadataObjectKind.TimeSeries))
            {
                foreach (IMetadataObjectDescriptor desc2 in desc.Bind().WalkNecessaryObjects())
                {
                    if (desc2.Id == desc.Id)
                    {
                        usings.Add(desc);
                        usingDAFCObjectsString = usingDAFCObjectsString + desc.ToString() + ", ";
                        break;
                    }
                }
            }
            if (!string.IsNullOrEmpty(usingDAFCObjectsString))
            {
                usingDAFCObjectsString = usingDAFCObjectsString.Substring(0, usingDAFCObjectsString.Length - 2);
                if (GeneralMethods.ShowWarning(Resources.BI_PROJECTEXPLORER_CALENDARDIMENSION_USED_QUESTION + usingDAFCObjectsString, MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    args.Cancel = true;
                    return;
                }
            }
            try
            {
                cdim.SetStartPoint((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
            foreach (IMetadataObjectDescriptor desc in usings)
            {
                IDateAndFactCorrelations dafc = desc.Bind() as IDateAndFactCorrelations;                
                dafc.ClearValuesOutOfDate();
            }
        }

        /// <summary>
        /// Обрабатывает смену конечной точки календарного измерения
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void tillBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalendarDimension cdim = itemDescriptor.Bind() as ICalendarDimension;
            string usingDAFCObjectsString = string.Empty;
            var usings = new List<MetadataObjectDescriptor>();            
            foreach (IMetadataObjectDescriptor desc in ProjectLink.RepositoryLink.WalkObjects(MetadataObjectKind.Cube, MetadataObjectKind.TimeSeries))
            {
                foreach (IMetadataObjectDescriptor desc2 in desc.Bind().WalkNecessaryObjects())
                {
                    if (desc.Id == desc2.Id)
                    {
                        usingDAFCObjectsString = usingDAFCObjectsString + desc.ToString() + ", ";                                
                        break;
                    }
                }
            }

            if (!string.IsNullOrEmpty(usingDAFCObjectsString))
            {
                usingDAFCObjectsString = usingDAFCObjectsString.Substring(0, usingDAFCObjectsString.Length - 2);
                if (GeneralMethods.ShowWarning(Resources.BI_PROJECTEXPLORER_CALENDARDIMENSION_USED_QUESTION + usingDAFCObjectsString, MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    args.Cancel = true;
                    return;
                }
            }
            try
            {
                cdim.SetEndPoint((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
            foreach (IMetadataObjectDescriptor desc in usings)
            {
                IDateAndFactCorrelations dafc = desc.Bind() as IDateAndFactCorrelations;                
                dafc.ClearValuesOutOfDate();
            }
        }

        /// <summary>
        /// Создает элементы управления структурой календарного измерения
        /// </summary>
        private void PutStructureControlsForCalendarDimension()
        {
            Panel dynlabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label dynLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALENDARDIMENSION_DYNAMICS,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = dynlabPanel,
                Dock = DockStyle.Bottom
            };
            dynlabPanel.Height = dynLabel.Height + dynLabel.Font.Height;
            dynlabPanel.Parent = ObjectStructureArea;
            dynlabPanel.Top = 0;
            dynlabPanel.Left = 0;
            dynlabPanel.Width = ObjectStructureArea.Width;
            dynlabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _dynBox = new ComboBox()
            {
                Name = "dynBox",
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            for (int i = 1; i < 4; i++)
            {
                _dynBox.Items.Add(MetadataSharedMethods.GetDynamicsName((CalendarDynamics)i));
            }
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalendarDimension cdim = itemDescriptor.Bind() as ICalendarDimension;
            _dynBox.SelectedItem = MetadataSharedMethods.GetDynamicsName(cdim.GetDynamics());
            _dynBox.SelectedIndexChanged += new EventHandler(dynBox_SelectedIndexChanged);
            _dynBox.Parent = ObjectStructureArea;
            _dynBox.Top = dynlabPanel.Height;
            _dynBox.Left = 0;
            _dynBox.Width = ObjectStructureArea.Width;
            _dynBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel fromlabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label fromLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALENDARDIMENSION_FROM,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = fromlabPanel,
                Dock = DockStyle.Bottom
            };
            fromlabPanel.Height = fromLabel.Height + fromLabel.Font.Height;
            fromlabPanel.Parent = ObjectStructureArea;
            fromlabPanel.Top = _dynBox.Top + _dynBox.Height;
            fromlabPanel.Left = 0;
            fromlabPanel.Width = ObjectStructureArea.Width;
            fromlabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _fromDateBox = new DateTimePicker()
            {
                Name = "fromBox",
                ShowUpDown = true,
                Format = DateTimePickerFormat.Long,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_fromDateBox, cdim.GetDynamics());
            _fromDateBox.Value = cdim.StartPoint;
            _fromDateBox.Validating += new CancelEventHandler(fromBox_Validating);
            _fromDateBox.Parent = ObjectStructureArea;
            _fromDateBox.Top = fromlabPanel.Top + fromlabPanel.Height;
            _fromDateBox.Left = 0;
            _fromDateBox.Width = ObjectStructureArea.Width;
            _fromDateBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel tilllabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label tillLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALENDARDIMENSION_TILL,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = tilllabPanel,
                Dock = DockStyle.Bottom
            };
            tilllabPanel.Height = tillLabel.Height + tillLabel.Font.Height;
            tilllabPanel.Parent = ObjectStructureArea;
            tilllabPanel.Top = _fromDateBox.Top + _fromDateBox.Height;
            tilllabPanel.Left = 0;
            tilllabPanel.Width = ObjectStructureArea.Width;
            tilllabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _tillDateBox = new DateTimePicker()
            {
                Name = "tillBox",
                ShowUpDown = true,
                Format = DateTimePickerFormat.Long,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_tillDateBox, cdim.GetDynamics());
            _tillDateBox.Value = cdim.EndPoint;
            _tillDateBox.Validating += new CancelEventHandler(tillBox_Validating);
            _tillDateBox.Parent = ObjectStructureArea;
            _tillDateBox.Top = tilllabPanel.Top + tilllabPanel.Height;
            _tillDateBox.Left = 0;
            _tillDateBox.Width = ObjectStructureArea.Width;
            _tillDateBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
        }

        /// <summary>
        /// Обрабатывает смену целевого объекта в ярлыке
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void aimBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            IShortcut shortcut = itemDescriptor.Bind() as IShortcut;
            ComboBox aimBox = sender as ComboBox;
            if (aimBox.SelectedIndex == 0)
            {
                //<не выбран>
                shortcut.SetAim(null);
                return;
            }
            try
            {
                shortcut.SetAim((aimBox.Tag as List<IMetadataObjectDescriptor>)[aimBox.SelectedIndex]);
            }
            catch (BIShortcutOnShortcutException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                aimBox.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// Создает элементы управления структурой ссылки
        /// </summary>
        private void PutStructureControlsForShortcut()
        {
            Panel aimlabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label aimLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_SHORTCUT_METADATAOBJECT,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = aimlabPanel,
                Dock = DockStyle.Bottom
            };
            aimlabPanel.Height = aimLabel.Height + aimLabel.Font.Height;
            aimlabPanel.Parent = ObjectStructureArea;
            aimlabPanel.Top = 0;
            aimlabPanel.Left = 0;
            aimlabPanel.Width = ObjectStructureArea.Width;
            aimlabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            ComboBox aimBox = new ComboBox()
            {
                Name = "aimBox",
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            List<IMetadataObjectDescriptor> links = new List<IMetadataObjectDescriptor>();
            aimBox.Items.Add(Resources.BI_PROJECTEXPLORER_SHORTCUT_EMPTY);
            links.Add(null);
            foreach(IMetadataObjectDescriptor desc in _projectLink.RepositoryLink.GetObjectsDescriptors())
            {
                aimBox.Items.Add(desc.ToString());
                links.Add(desc);
            }
            aimBox.Tag = links;
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            IShortcut shortcut = itemDescriptor.Bind() as IShortcut;
            aimBox.SelectedItem = shortcut.GetShortcutType() == ShortcutType.MetadataObject ? (shortcut.GetAim() as IMetadataObjectDescriptor).ToString() : Resources.BI_PROJECTEXPLORER_SHORTCUT_EMPTY;
            aimBox.SelectedIndexChanged += new EventHandler(aimBox_SelectedIndexChanged);
            aimBox.Parent = ObjectStructureArea;
            aimBox.Top = aimlabPanel.Height;
            aimBox.Left = 0;
            aimBox.Width = ObjectStructureArea.Width;
            aimBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;            
        }

        /// <summary>
        /// Создает элементы управления структурой модели
        /// </summary>
        private void PutStructureControlsForModel()
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            IModel model = itemDescriptor.Bind() as IModel;
            Panel dynlabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label dynLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALENDARDIMENSION_DYNAMICS,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = dynlabPanel,
                Dock = DockStyle.Bottom
            };
            dynlabPanel.Height = dynLabel.Height + dynLabel.Font.Height;
            dynlabPanel.Parent = ObjectStructureArea;
            dynlabPanel.Top = 0;
            dynlabPanel.Left = 0;
            dynlabPanel.Width = ObjectStructureArea.Width;
            dynlabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _dynBox = new ComboBox()
            {
                Name = "dynBox",
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            for (int i = 1; i < 4; i++)
            {
                _dynBox.Items.Add(MetadataSharedMethods.GetDynamicsName((CalendarDynamics)i));
            }
            _dynBox.SelectedItem = MetadataSharedMethods.GetDynamicsName(model.GetDynamics());
            _dynBox.SelectedIndexChanged += new EventHandler(modeldynBox_SelectedIndexChanged);
            _dynBox.Parent = ObjectStructureArea;
            _dynBox.Top = dynlabPanel.Height;
            _dynBox.Left = 0;
            _dynBox.Width = ObjectStructureArea.Width;
            _dynBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            Panel identfromlabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label identfromLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_IDENTFROM,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = identfromlabPanel,
                Dock = DockStyle.Bottom
            };
            identfromlabPanel.Height = identfromLabel.Height + identfromLabel.Font.Height;
            identfromlabPanel.Parent = ObjectStructureArea;
            identfromlabPanel.Top = _dynBox.Top + _dynBox.Height;
            identfromlabPanel.Left = 0;
            identfromlabPanel.Width = ObjectStructureArea.Width;
            identfromlabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _identfromBox = new DateTimePicker()
            {
                Name = "identfromBox",
                ShowUpDown = true,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_identfromBox, model.GetDynamics());
            _identfromBox.Value = model.GetIdentificationStart();
            _identfromBox.Validating += new CancelEventHandler(modelidentfromBox_Validating);
            _identfromBox.Parent = ObjectStructureArea;
            _identfromBox.Top = identfromlabPanel.Top + identfromlabPanel.Height;
            _identfromBox.Left = 0;
            _identfromBox.Width = ObjectStructureArea.Width;
            _identfromBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel identtilllabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label identtillLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_IDENTTILL,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = identtilllabPanel,
                Dock = DockStyle.Bottom
            };
            identtilllabPanel.Height = identtillLabel.Height + identtillLabel.Font.Height;
            identtilllabPanel.Parent = ObjectStructureArea;
            identtilllabPanel.Top = _identfromBox.Top + _identfromBox.Height;
            identtilllabPanel.Left = 0;
            identtilllabPanel.Width = ObjectStructureArea.Width;
            identtilllabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _identtillBox = new DateTimePicker()
            {
                Name = "identtillBox",
                ShowUpDown = true,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_identtillBox, model.GetDynamics());
            _identtillBox.Value = model.GetIdentificationEnd();
            _identtillBox.Validating += new CancelEventHandler(modelidenttillBox_Validating);
            _identtillBox.Parent = ObjectStructureArea;
            _identtillBox.Top = identtilllabPanel.Top + identtilllabPanel.Height;
            _identtillBox.Left = 0;
            _identtillBox.Width = ObjectStructureArea.Width;
            _identtillBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel forefromlabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label forefromLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_FOREFROM,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = forefromlabPanel,
                Dock = DockStyle.Bottom
            };
            forefromlabPanel.Height = forefromLabel.Height + forefromLabel.Font.Height;
            forefromlabPanel.Parent = ObjectStructureArea;
            forefromlabPanel.Top = _identtillBox.Top + _identtillBox.Height;
            forefromlabPanel.Left = 0;
            forefromlabPanel.Width = ObjectStructureArea.Width;
            forefromlabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _forefromBox = new DateTimePicker()
            {
                Name = "forefromBox",
                ShowUpDown = true,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_forefromBox, model.GetDynamics());
            _forefromBox.Value = model.GetForecastStart();
            _forefromBox.Validating += new CancelEventHandler(modelforefromBox_Validating);
            _forefromBox.Parent = ObjectStructureArea;
            _forefromBox.Top = forefromlabPanel.Top + forefromlabPanel.Height;
            _forefromBox.Left = 0;
            _forefromBox.Width = ObjectStructureArea.Width;
            _forefromBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel foretilllabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label foretillLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_FORETILL,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = foretilllabPanel,
                Dock = DockStyle.Bottom
            };
            foretilllabPanel.Height = foretillLabel.Height + foretillLabel.Font.Height;
            foretilllabPanel.Parent = ObjectStructureArea;
            foretilllabPanel.Top = _forefromBox.Top + _forefromBox.Height;
            foretilllabPanel.Left = 0;
            foretilllabPanel.Width = ObjectStructureArea.Width;
            foretilllabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _foretillBox = new DateTimePicker()
            {
                Name = "foretillBox",
                ShowUpDown = true,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_foretillBox, model.GetDynamics());
            _foretillBox.Value = model.GetForecastEnd();
            _foretillBox.Validating += new CancelEventHandler(modelforetillBox_Validating);
            _foretillBox.Parent = ObjectStructureArea;
            _foretillBox.Top = foretilllabPanel.Top + foretilllabPanel.Height;
            _foretillBox.Left = 0;
            _foretillBox.Width = ObjectStructureArea.Width;
            _foretillBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel labelPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label modelsLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_MODELS,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = labelPanel,
                Dock = DockStyle.Top
            };
        }

        /// <summary>
        /// Обрабатывает смену начальной точки периода идентификации в модели
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void modelidentfromBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            IModel model = itemDescriptor.Bind() as IModel;
            try
            {
                model.SetIdentificationStart((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Обрабатывает смену конечной точки периода идентификации в модели
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void modelidenttillBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            IModel model = itemDescriptor.Bind() as IModel;
            try
            {
                model.SetIdentificationEnd((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Обрабатывает смену начальной точки периода прогнозирования в модели
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void modelforefromBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            IModel model = itemDescriptor.Bind() as IModel;
            try
            {
                model.SetForecastStart((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Обрабатывает смену конечной точки периода прогнозирования в модели
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void modelforetillBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            IModel model = itemDescriptor.Bind() as IModel;
            try
            {
                model.SetForecastEnd((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Обрабатывает смену начальной точки периода идентификации в расчете
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void calcidentfromBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalculation calc = itemDescriptor.Bind() as ICalculation;
            try
            {
                calc.SetIdentificationStart((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Обрабатывает смену конечной точки периода идентификации в расчете
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void calcidenttillBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalculation calc = itemDescriptor.Bind() as ICalculation;
            try
            {
                calc.SetIdentificationEnd((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Обрабатывает смену начальной точки периода прогнозирования в расчете
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void calcforefromBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalculation calc = itemDescriptor.Bind() as ICalculation;
            try
            {
                calc.SetForecastStart((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Обрабатывает смену конечной точки периода прогнозирования в расчете
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void calcforetillBox_Validating(object sender, CancelEventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalculation calc = itemDescriptor.Bind() as ICalculation;
            try
            {
                calc.SetForecastEnd((sender as DateTimePicker).Value);
            }
            catch (BICalendarStartDateAfterEndDateException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                args.Cancel = true;
                return;
            }
        }

        /// <summary>
        /// Обрабатывает нажатие кнопок в гриде моделей расчета
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ProcessCalculationModelsChange(object sender, DataGridViewCellEventArgs args)
        {
            if (args.RowIndex >= 0)
            {
                IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
                ICalculation calc = itemDescriptor.Bind() as ICalculation;
                if (args.ColumnIndex == _grdFields.Columns["delColumn"].Index)
                {
                    //удаление модели
                    calc.RemoveModelByIndex(args.RowIndex);
                }
                if ((args.ColumnIndex == _grdFields.Columns["upColumn"].Index) && (args.RowIndex >= 1))
                {
                    calc.UpModel(args.RowIndex);
                }
                if ((args.ColumnIndex == _grdFields.Columns["downColumn"].Index) && (args.RowIndex < (_grdFields.RowCount - 1)))
                {
                    calc.DownModel(args.RowIndex);
                }
                UpdateObjectProperties();
            }
        }

        /// <summary>
        /// Изменяет используемое календарное измерение расчета
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void ChangeCalendarDimensionInCalculation(object sender, EventArgs args)
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalculation calc = itemDescriptor.Bind() as ICalculation;
            string dimlabel = (_toolFields.Items["calendarDimensionNameBox"] as ToolStripComboBox).SelectedItem as string;
            calc.SetCalendarDimension(ProjectLink.RepositoryLink.GetObjectDescriptorByLabel(dimlabel, MetadataObjectKind.Dimension) as ICalendarDimension);
            UpdateObjectProperties();
        }

        /// <summary>
        /// Создает элементы управления структурой расчета
        /// </summary>
        private void PutStructureControlsForCalculation()
        {
            IMetadataObjectDescriptor itemDescriptor = ObjectsList.SelectedItems[0].Tag as IMetadataObjectDescriptor;
            ICalculation calc = itemDescriptor.Bind() as ICalculation;
            _toolFields = new ToolStrip();
            _toolFields.Parent = ObjectStructureArea;
            _toolFields.Dock = DockStyle.Top;
            ToolStripComboBox tsi = new ToolStripComboBox("calendarDimensionNameBox")
            {
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            ComboBox.ObjectCollection items = tsi.Items;
            items.Clear();
            foreach (MetadataObjectDescriptor info in ProjectLink.RepositoryLink.GetObjectsDescriptors(MetadataObjectKind.Dimension))
            {                
                if ((DimensionKind)info.Subkind != DimensionKind.Calendar)
                    continue;
                items.Add(info.Label);
            }
            ICalendarDimension caldim = null;
            if (Assert.FailIf(tsi.Items.Count == 0, Assert.Id.Assert00125))//не должно такого быть
            //(если расчет создался значит в репозитории есть
            //хотя бы одно календарное измерение)            
            {
                caldim = calc.GetCalendarDimension();
                if (caldim == null)
                {
                    tsi.SelectedIndex = 0;
                }
                else
                {
                    tsi.SelectedItem = caldim.Label;
                }
            }
            caldim = _projectLink.RepositoryLink.GetObjectDescriptorByLabel(tsi.SelectedItem as string, MetadataObjectKind.Dimension).Bind() as ICalendarDimension;
            _toolFields.Items.Add(tsi);
            _toolFields.Items.Add(Resources.BI_PROJECTEXPLORER_CALCULATION_CHANGECALDIM, SoftwareConsulting.BI11.Studio.UI.Properties.Resources.apply, ChangeCalendarDimensionInCalculation);
            _toolFields.Items[_toolFields.Items.Count - 1].Name = "changeDimensionButton";
            _toolFields.Items["changeDimensionButton"].DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
            _toolFields.Items["changeDimensionButton"].TextImageRelation = TextImageRelation.ImageBeforeText;
            _toolFields.Items["changeDimensionButton"].ImageTransparentColor = Color.Magenta;
            _toolFields.Items["changeDimensionButton"].Enabled = true;
            Panel identfromlabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label identfromLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_IDENTFROM,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = identfromlabPanel,
                Dock = DockStyle.Bottom
            };
            identfromlabPanel.Height = identfromLabel.Height + identfromLabel.Font.Height;
            identfromlabPanel.Parent = ObjectStructureArea;
            identfromlabPanel.Top = _toolFields.Height;
            identfromlabPanel.Left = 0;
            identfromlabPanel.Width = ObjectStructureArea.Width;
            identfromlabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _identfromBox = new DateTimePicker()
            {
                Name = "identfromBox",
                ShowUpDown = true,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_identfromBox, caldim.GetDynamics());
            _identfromBox.Value = calc.GetIdentificationStart();
            _identfromBox.Validating += new CancelEventHandler(calcidentfromBox_Validating);
            _identfromBox.Parent = ObjectStructureArea;
            _identfromBox.Top = identfromlabPanel.Top + identfromlabPanel.Height;
            _identfromBox.Left = 0;
            _identfromBox.Width = ObjectStructureArea.Width;
            _identfromBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel identtilllabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label identtillLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_IDENTTILL,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = identtilllabPanel,
                Dock = DockStyle.Bottom
            };
            identtilllabPanel.Height = identtillLabel.Height + identtillLabel.Font.Height;
            identtilllabPanel.Parent = ObjectStructureArea;
            identtilllabPanel.Top = _identfromBox.Top + _identfromBox.Height;
            identtilllabPanel.Left = 0;
            identtilllabPanel.Width = ObjectStructureArea.Width;
            identtilllabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _identtillBox = new DateTimePicker()
            {
                Name = "identtillBox",
                ShowUpDown = true,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_identtillBox, caldim.GetDynamics());
            _identtillBox.Value = calc.GetIdentificationEnd();
            _identtillBox.Validating += new CancelEventHandler(calcidenttillBox_Validating);
            _identtillBox.Parent = ObjectStructureArea;
            _identtillBox.Top = identtilllabPanel.Top + identtilllabPanel.Height;
            _identtillBox.Left = 0;
            _identtillBox.Width = ObjectStructureArea.Width;
            _identtillBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel forefromlabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label forefromLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_FOREFROM,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = forefromlabPanel,
                Dock = DockStyle.Bottom
            };
            forefromlabPanel.Height = forefromLabel.Height + forefromLabel.Font.Height;
            forefromlabPanel.Parent = ObjectStructureArea;
            forefromlabPanel.Top = _identtillBox.Top + _identtillBox.Height;
            forefromlabPanel.Left = 0;
            forefromlabPanel.Width = ObjectStructureArea.Width;
            forefromlabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _forefromBox = new DateTimePicker()
            {
                Name = "forefromBox",
                ShowUpDown = true,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_forefromBox, caldim.GetDynamics());
            _forefromBox.Value = calc.GetForecastStart();
            _forefromBox.Validating += new CancelEventHandler(calcforefromBox_Validating);
            _forefromBox.Parent = ObjectStructureArea;
            _forefromBox.Top = forefromlabPanel.Top + forefromlabPanel.Height;
            _forefromBox.Left = 0;
            _forefromBox.Width = ObjectStructureArea.Width;
            _forefromBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel foretilllabPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label foretillLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_FORETILL,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = foretilllabPanel,
                Dock = DockStyle.Bottom
            };
            foretilllabPanel.Height = foretillLabel.Height + foretillLabel.Font.Height;
            foretilllabPanel.Parent = ObjectStructureArea;
            foretilllabPanel.Top = _forefromBox.Top + _forefromBox.Height;
            foretilllabPanel.Left = 0;
            foretilllabPanel.Width = ObjectStructureArea.Width;
            foretilllabPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _foretillBox = new DateTimePicker()
            {
                Name = "foretillBox",
                ShowUpDown = true,
                MinDate = Constants.NullDate,
                MaxDate = (new DateTime(2000, 01, 01)).Add((new DateTime(2000, 01, 01)) - Constants.NullDate)
            };
            UpdateDateTimePickerFormat(_foretillBox, caldim.GetDynamics());
            _foretillBox.Value = calc.GetForecastEnd();
            _foretillBox.Validating += new CancelEventHandler(calcforetillBox_Validating);
            _foretillBox.Parent = ObjectStructureArea;
            _foretillBox.Top = foretilllabPanel.Top + foretilllabPanel.Height;
            _foretillBox.Left = 0;
            _foretillBox.Width = ObjectStructureArea.Width;
            _foretillBox.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;

            Panel labelPanel = new Panel()
            {
                BorderStyle = BorderStyle.None
            };
            Label modelsLabel = new Label()
            {
                Text = Resources.BI_PROJECTEXPLORER_CALCULATION_MODELS,
                TextAlign = ContentAlignment.MiddleCenter,
                Parent = labelPanel,
                Dock = DockStyle.Top
            };
            labelPanel.Height = modelsLabel.Height;
            labelPanel.Parent = ObjectStructureArea;
            labelPanel.Top = _foretillBox.Top + _foretillBox.Height;
            labelPanel.Left = 0;
            labelPanel.Width = ObjectStructureArea.Width;
            labelPanel.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _modelsTools = new ToolStrip();
            //_modelsTools.Dock = DockStyle.Top;
            tsi = new ToolStripComboBox("newModelNameBox")
            {
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            items = tsi.Items;
            items.Clear();
            foreach (MetadataObjectDescriptor info in ProjectLink.RepositoryLink.GetObjectsDescriptors(MetadataObjectKind.Model))
            {
                items.Add(info.Label);
            }
            if (tsi.Items.Count > 0)
            {
                tsi.SelectedIndex = 0;
            }
            _modelsTools.Items.Add(tsi);
            _modelsTools.Items.Add(Resources.BI_PROJECTEXPLORER_CALCULATION_ADDMODEL_CAPTION, SoftwareConsulting.BI11.Studio.UI.Properties.Resources.plus, AddModelToCalculation);
            _modelsTools.Items[_toolFields.Items.Count - 1].Name = "addModelButton";
            _modelsTools.Items["addModelButton"].DisplayStyle = ToolStripItemDisplayStyle.ImageAndText;
            _modelsTools.Items["addModelButton"].TextImageRelation = TextImageRelation.ImageBeforeText;
            _modelsTools.Items["addModelButton"].ImageTransparentColor = Color.Magenta;
            _modelsTools.Items["addModelButton"].Enabled = tsi.Items.Count > 0;
            _modelsTools.Parent = ObjectStructureArea;
            _modelsTools.Top = labelPanel.Top + labelPanel.Height;
            _modelsTools.Width = ObjectStructureArea.Width;
            _modelsTools.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;
            _grdFields = new DataGridView();
            _grdFields.MultiSelect = false;
            _grdFields.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            _grdFields.AllowUserToOrderColumns = true;
            _grdFields.ShowEditingIcon = false;
            _grdFields.ShowRowErrors = false;
            _grdFields.RowHeadersVisible = false;
            _grdFields.ColumnHeadersVisible = true;
            _grdFields.AllowUserToAddRows = false;
            _grdFields.AllowUserToDeleteRows = false;
            DataGridViewTextBoxColumn modelColumn = new DataGridViewTextBoxColumn()
            {
                HeaderText = Resources.BI_PROJECTEXPLORER_CALCULATION_MODEL,
                Name = "modelColumn",
                ReadOnly = true,
                Resizable = DataGridViewTriState.True,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            };
            _grdFields.Columns.Add(modelColumn);
            DataGridViewButtonColumn delColumn = new DataGridViewButtonColumn()
            {
                HeaderText = string.Empty,
                Name = "delColumn",
                ReadOnly = false,
                Resizable = DataGridViewTriState.False,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            };
            _grdFields.Columns.Add(delColumn);
            DataGridViewButtonColumn upColumn = new DataGridViewButtonColumn()
            {
                HeaderText = string.Empty,
                Name = "upColumn",
                ReadOnly = false,
                Resizable = DataGridViewTriState.False,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            };
            _grdFields.Columns.Add(upColumn);
            DataGridViewButtonColumn downColumn = new DataGridViewButtonColumn()
            {
                HeaderText = string.Empty,
                Name = "downColumn",
                ReadOnly = false,
                Resizable = DataGridViewTriState.False,
                AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
            };
            _grdFields.Columns.Add(downColumn);
            _grdFields.CellContentClick += ProcessCalculationModelsChange;
            _grdFields.Parent = ObjectStructureArea;
            _grdFields.Top = _modelsTools.Top + _modelsTools.Height;
            _grdFields.Left = 0;
            _grdFields.Width = ObjectStructureArea.Width;
            _grdFields.Height = ObjectStructureArea.Height - labelPanel.Height - _toolFields.Height;
            _grdFields.Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom;
            int c = calc.GetModelsCount();
            for (int i = 0; i < c; i++)
            {
                IModel model = calc.GetModelByIndex(i);
                _grdFields.Rows.Add();
                DataGridViewRow row = _grdFields.Rows[_grdFields.Rows.Count - 1];
                row.Cells["modelColumn"].Value = model.Label;
                DataGridViewButtonCell buttoncell = row.Cells["delColumn"] as DataGridViewButtonCell;
                buttoncell.Value = Resources.BI_PROJECTEXPLORER_CALCULATION_REMOVEMODEL;
                buttoncell = row.Cells["upColumn"] as DataGridViewButtonCell;
                if (i > 0)
                {
                    buttoncell.Value = "^";
                }
                buttoncell = row.Cells["downColumn"] as DataGridViewButtonCell;
                if (i < c - 1)
                {
                    buttoncell.Value = "v";
                }
            }
        }

        /// <summary>
        /// Обновляет заголовок области свойств объекта
        /// </summary>
        private void UpdateObjectPropertiesCaption()
        {
            MetadataObjectDescriptor info = (MetadataObjectDescriptor)ObjectsList.SelectedItems[0].Tag;            
            ObjectPropertiesArea.Text = string.Format(Resources.BI_PROJECTEXPLORER_OBJECTPROPERTIES_CAPTION, info.Kind.ToUserString(), info.Name);            
        }

        /// <summary>
        /// Обновляет область свойств объекта
        /// </summary>
        private void UpdateObjectProperties()
        {            
            Control.ControlCollection controls = ObjectStructureArea.Controls;                
            ListView.SelectedListViewItemCollection sel = ObjectsList.SelectedItems;            
            if (sel.Count == 1)
            {             
                //выделен ровно один объект, можно отобразить его свойства
                ListViewItem item = sel[0];
                IMetadataObjectDescriptor desc = item.Tag as IMetadataObjectDescriptor;
                //сначала пополним историю если надо..
                PutHistoryPoint(desc, MetadataObjectsHistoryPointKind.SimpleMetadataObject);
                if (_handheldPropertiesClose)            
                    return;
                //..затем отобразим свойства
                controls.Clear();
                ObjectPropertiesArea.CaptionImage = desc.GetImage(MetadataObjectImageSize.Normal, MetadataObjectState.Normal);
                UpdateObjectPropertiesCaption();
                SelectedObjectLabelBox.Text = desc.Label;
                string descriptionText = Resources.BI_PROJECTEXPLORER_ENTERDESCRIPTION;
                string realDescription = string.Empty;                                    
                realDescription = desc.Description;
                if (string.IsNullOrEmpty(realDescription))
                {
                    SelectedObjectDescriptionBox.ForeColor = SystemColors.GrayText;
                }
                else
                {
                    descriptionText = realDescription;
                    SelectedObjectDescriptionBox.ForeColor = SystemColors.WindowText;
                }
                SelectedObjectDescriptionBox.Text = descriptionText;                
                SelectedObjectLabelBox.Visible = true;
                SelectedObjectDescriptionBox.Visible = true;
                switch (desc.Kind)
                {
                    case MetadataObjectKind.Folder:
                        //никаких настроек нет
                        break;
                    case MetadataObjectKind.Indicator:
                        //никаких настроек нет
                        break;
                    case MetadataObjectKind.Table:
                        PutStructureControlsForTable();
                        break;
                    case MetadataObjectKind.Dimension:                        
                        switch((DimensionKind)desc.Subkind)
                        {
                            case DimensionKind.Facts:
                                PutStructureControlsForFactsDimension();
                                break;
                            default:
                                PutStructureControlsForCalendarDimension();
                                break;
                        }
                        break;
                    case MetadataObjectKind.Cube:
                        PutStructureControlsForCube();
                        break;
                    case MetadataObjectKind.TimeSeries:
                        //никаких настроек нет, т.к.
                        //вся структура временного ряда определяется
                        //его календарным измерением, а оно берется
                        //из активного расчета, и измерением миров
                        //а оно неизменно
                        break;
                    case MetadataObjectKind.Model:
                        PutStructureControlsForModel();
                        break;                    
                    case MetadataObjectKind.Calculation:
                        PutStructureControlsForCalculation();
                        break;
                    case MetadataObjectKind.ClassificationProblem:
                        //никаких настроек нет
                        break;
                    case MetadataObjectKind.ActionSet:
                        //никаких настроек нет                        
                        break;
                    case MetadataObjectKind.Shortcut:
                        PutStructureControlsForShortcut();
                        break;
                }
                ObjectPropertiesArea.Visible = true;
                UpdateViewAbilities(false);
            }
            else
            {   
                if (_handheldPropertiesClose)            
                    return;
                controls.Clear();
                ObjectPropertiesArea.Visible = false;
                ObjectPropertiesArea.Text = string.Empty;
                ObjectPropertiesArea.CaptionImage = null;                
                SelectedObjectLabelBox.Text = string.Empty;
                SelectedObjectDescriptionBox.Text = string.Empty;                
                SelectedObjectLabelBox.Visible = false;
                SelectedObjectDescriptionBox.Visible = false;
                UpdateViewAbilities(false);
            }                            
        }

        /// <summary>
        /// Актуализирует информацию о типе объектов в области объектов
        /// </summary>
        private void ActualizeInfoAboutObjectTypes()
        {
            int index = ObjectKindsView.SelectedItems[0].Index;
            MetadataObjectKind objKind = MetadataObjectKind.None; //по умолчанию считаем, что выбраны "все типы", внутри этой процедуры будем считать что это None
            if (Enum.IsDefined(typeof(MetadataObjectKind), index + 2))//+2, т.к. None и Folder недоступны для выбора
                objKind = (MetadataObjectKind)(index + 2);//+2, т.к. None и Folder недоступны для выбора
            switch (objKind)
            {                
                case MetadataObjectKind.Situation:
                    SetTreeEnable(false);
                    EnableObjectsTreeButton.SetState(EnableObjectsTreeButton.State | RibbonItemChangedStates.Disabled);                    
                    VisibleTypes = new MetadataObjectsVisibleTypes()
                    {
                        Kind = MetadataObjectKind.Situation,
                        All = false
                    };
                    if (_situationsBoxPanel == null)
                    {
                        _situationsAreaTip = new ToolStrip();
                        _situationsAreaTip.GripStyle = ToolStripGripStyle.Hidden;
                        _situationsAreaTip.Parent = ToolsContainer.ContentPanel;
                        _situationsAreaTip.Dock = DockStyle.Top;
                        _situationsBoxPanel = new Panel();
                        _situationsBoxPanel.Parent = ToolsContainer.ContentPanel;
                        _situationsBoxPanel.AutoScroll = true;
                        _situationsBoxPanel.Location = new Point(0, KindsSplitter.Left + KindsSplitter.Width + 1);
                        _situationsBoxPanel.Dock = DockStyle.Fill;
                        _situationsBox = new CorrelationsBox();
                        _situationsBox.Parent = _situationsBoxPanel;
                        _situationsBox.Location = new Point(0, 0);
                        _situationsBox.Size = new Size(10000, 10000);
                        _situationsBox.AreaSize = new Size(10000, 10000);
                        _situationsBox.EntityBackColors[1] = SystemColors.InactiveCaption;
                        foreach (SituationBox sitbox in _MainFormLink.HierarchyForm.CurrentSituationsArea)
                        {
                            _situationsBox.AddEntity(sitbox.Name, new Point(sitbox.X, sitbox.Y), 1);
                        }
                        _situationsBox.BorderStyle = BorderStyle.FixedSingle;
                        _situationsBox.Visible = true;
                    }                    
                    _situationsAreaTip.Visible = true;
                    _situationsBoxPanel.BringToFront();
                    _situationsBoxPanel.Visible = true;
                    break;                
                case MetadataObjectKind.None:
                    VisibleTypes = new MetadataObjectsVisibleTypes()
                    {
                        Kind = MetadataObjectKind.None,
                        All = true
                    };
                    break;
                default:
                    VisibleTypes = new MetadataObjectsVisibleTypes()
                    {
                        Kind = objKind,
                        All = false
                    };
                    break;                
            }
            if (VisibleTypes.Kind != MetadataObjectKind.Situation)
            {
                EnableObjectsTreeButton.SetState(EnableObjectsTreeButton.State & ~RibbonItemChangedStates.Disabled);
                if (_situationsBoxPanel != null)
                {
                    _situationsBoxPanel.Visible = false;
                    _situationsBoxPanel.SendToBack();
                    _situationsAreaTip.Visible = false;
                }
            }
            SetRibbonViewKind(index);
            UpdateViewAbilities(false);
        }

        /// <summary>
        /// Возвращает ссылку на главную форму
        /// </summary>
        public MainForm MainFormLink
        {
            get
            {
                return _MainFormLink;
            }
        }

        /// <summary>
        /// Сохраняет репозиторий как...
        /// </summary>
        public void SaveRepository(string fileName)
        {
            _projectLink.RepositoryLink.FileName = fileName;
            _projectLink.RepositoryLink.SaveMe();
        }

        /// <summary>
        /// Обновляет название окна с учетом открытого проекта
        /// </summary>
        private void UpdateCaptionName()
        {
            UpdateCaptionName(true);
        }

        /// <summary>
        /// Обновляет название окна
        /// </summary>
        public void UpdateCaptionName(bool isProjectOpened)
        {
            this.Text = isProjectOpened ?
                string.Format(Resources.BI_FRAMECHILD_MASK, Resources.BI_PROJECTEXPLORER_CAPTION, _projectLink.Name)
                :
                Resources.BI_PROJECTEXPLORER_CAPTION;
        }

        /// <summary>
        /// Обработка завершения запуска программы
        /// </summary>
        private void ProcessProgramStarted()
        {
            _inObjectF2Renaming = false;
            _blockObjectsListAutoRefresh = false;
            UpdateCaptionName(false);
            _treeExpanded = new HashSet<Guid>();
            _beforeSelectedObjectsIds = new List<Guid>();
            _handheldPropertiesClose = false;
            _cutOperation = false;            
            _cuttedItemsDescriptors = new List<IMetadataObjectDescriptor>();
            _MainFormLink = new MainForm(this);
            _MainFormLink.Show();
            _projectLink = new ProjectDescriptor();
            _projectLink.CreateLIM();
            UpdateCaptionName();
            //грузим картинки    
            ObjectsList.SmallImageList = MetadataObjectsProcessor.GetAllImages(MetadataObjectImageSize.Small);            
            ObjectsList.LargeImageList = MetadataObjectsProcessor.GetAllImages(MetadataObjectImageSize.Large);
            ObjectsTree.ImageList = MetadataObjectsProcessor.GetAllImages(MetadataObjectImageSize.Small);            
            ObjectsTree.ImageKey = MetadataObjectKind.Folder.GetImageKey(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            ObjectsTree.SelectedImageKey = MetadataObjectKind.Folder.GetImageKey(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            ObjectKindsView.LargeImageList = MetadataObjectsProcessor.GetAllImages(MetadataObjectImageSize.Large);            
            ObjectKindsView.SmallImageList = MetadataObjectsProcessor.GetAllImages(MetadataObjectImageSize.Small);            
            foreach(MetadataObjectKind kind in MetadataSharedMethods.GetAllMetadataObjectKinds())
            {
                string largeImageKey = kind.GetImageKey(MetadataObjectImageSize.Large, MetadataObjectState.Normal);
                string normalImageKey = kind.GetImageKey(MetadataObjectImageSize.Normal, MetadataObjectState.Normal);
                string smallImageKey = kind.GetImageKey(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
                Image largeImage = MetadataObjectsProcessor.GetImage(largeImageKey, MetadataObjectImageSize.Large);
                Image normalImage = MetadataObjectsProcessor.GetImage(normalImageKey, MetadataObjectImageSize.Normal);
                Image smallImage = MetadataObjectsProcessor.GetImage(smallImageKey, MetadataObjectImageSize.Small);
                RibbonButton viewUsualButton = null;
                RibbonButton viewDropButton = null;
                RibbonButton createButton = null;
                ListViewItem viewItem = null;
                switch(kind)
                {
                    case MetadataObjectKind.Indicator:
                        viewUsualButton = ViewIndicatorsButton;
                        viewDropButton = ViewIndicatorsDropButton;
                        createButton = CreateIndicatorButton;
                        viewItem = ObjectKindsView.Items[0];
                        break;
                    case MetadataObjectKind.Situation:
                        viewUsualButton = ViewSituationsButton;
                        viewDropButton = ViewSituationsDropButton;
                        viewItem = ObjectKindsView.Items[1];
                        break;
                    case MetadataObjectKind.Table:
                        viewUsualButton = ViewTablesButton;
                        viewDropButton = ViewTablesDropButton;
                        createButton = CreateTableButton;
                        viewItem = ObjectKindsView.Items[2];
                        break;
                    case MetadataObjectKind.Dimension:
                        viewUsualButton = ViewDimensionsButton;
                        viewDropButton = ViewDimensionsDropButton;
                        createButton = CreateDimensionButton;
                        viewItem = ObjectKindsView.Items[3];
                        break;
                    case MetadataObjectKind.Cube:
                        viewUsualButton = ViewCubesButton;
                        viewDropButton = ViewCubesDropButton;
                        createButton = CreateCubeButton;
                        viewItem = ObjectKindsView.Items[4];
                        break;
                    case MetadataObjectKind.TimeSeries:
                        viewUsualButton = ViewTimeseriesButton;
                        viewDropButton = ViewTimeseriesDropButton;
                        createButton = CreateTimeseriesButton;
                        viewItem = ObjectKindsView.Items[5];
                        break;
                    case MetadataObjectKind.Model:
                        viewUsualButton = ViewModelsButton;
                        viewDropButton = ViewModelsDropButton;
                        createButton = CreateModelButton;
                        viewItem = ObjectKindsView.Items[6];
                        break;
                    case MetadataObjectKind.Calculation:
                        viewUsualButton = ViewCalculationsButton;
                        viewDropButton = ViewCalculationsDropButton;
                        createButton = CreateCalculationButton;
                        viewItem = ObjectKindsView.Items[7];
                        break;
                    case MetadataObjectKind.ClassificationProblem:
                        viewUsualButton = ViewClassificationProblemsButton;
                        viewDropButton = ViewClassificationProblemsDropButton;
                        createButton = CreateClassificationProblemButton;
                        viewItem = ObjectKindsView.Items[8];
                        break;
                    case MetadataObjectKind.ActionSet:
                        viewUsualButton = ViewActionsetsButton;
                        viewDropButton = ViewActionsetsDropButton;
                        createButton = CreateActionsetButton;
                        viewItem = ObjectKindsView.Items[9];
                        break;
                    case MetadataObjectKind.Shortcut:
                        viewUsualButton = ViewShortcutsButton;
                        viewDropButton = ViewShortcutsDropButton;
                        createButton = CreateShortcutButton;
                        viewItem = ObjectKindsView.Items[10];
                        break;
                    case MetadataObjectKind.Folder:                        
                        createButton = CreateFolderButton;                        
                        break;
                }
                if (viewUsualButton != null)
                {
                    viewUsualButton.Image = normalImage;
                    viewUsualButton.SmallImage = smallImage;
                }
                if (viewDropButton != null)
                {
                    viewDropButton.Image = normalImage;
                    viewDropButton.SmallImage = smallImage;
                }
                if (createButton != null)
                {                    
                    createButton.Image = normalImage;
                    createButton.SmallImage = smallImage;
                }
                if (viewItem != null)
                    viewItem.ImageKey = largeImageKey;
            }
            string largeImageKeyAllObjects = MetadataObjectsProcessor.GetImageKey(MetadataObjectImageSize.Large, MetadataObjectState.Normal);
            string normalImageKeyAllObjects = MetadataObjectsProcessor.GetImageKey(MetadataObjectImageSize.Normal, MetadataObjectState.Normal);
            string smallImageKeyAllObjects = MetadataObjectsProcessor.GetImageKey(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
            Image largeImageAllObjects = MetadataObjectsProcessor.GetImage(largeImageKeyAllObjects, MetadataObjectImageSize.Large);
            Image normalImageAllObjects = MetadataObjectsProcessor.GetImage(normalImageKeyAllObjects, MetadataObjectImageSize.Normal);
            Image smallImageAllObjects = MetadataObjectsProcessor.GetImage(smallImageKeyAllObjects, MetadataObjectImageSize.Small);
            ViewAllObjectsButton.Image = normalImageAllObjects;
            ViewAllObjectsButton.SmallImage = smallImageAllObjects;
            ViewAllObjectsDropButton.Image = normalImageAllObjects;
            ViewAllObjectsDropButton.SmallImage = smallImageAllObjects;
            ObjectKindsView.Items[ObjectKindsView.Items.Count - 1].ImageKey = largeImageKeyAllObjects;            
            //кончили грузить картинки
            _blockRibbon = false;
            OpenProjectDialog.Filter = Resources.BI_PROJECT_FILTER + "|*" + ProjectDescriptor.FileNameExtension;
            OpenProjectDialog.CheckPathExists = true;
            OpenProjectDialog.CheckFileExists = true;
            OpenProjectDialog.DefaultExt = "*" + ProjectDescriptor.FileNameExtension;
            SaveProjectDialog.OverwritePrompt = true;
            SaveProjectDialog.Filter = Resources.BI_PROJECT_FILTER + "|*" + ProjectDescriptor.FileNameExtension;
            SaveProjectDialog.CheckPathExists = true;
            SaveProjectDialog.DefaultExt = "*" + ProjectDescriptor.FileNameExtension;
            _programFocusChange = false;
            _programKindChange = false;
            //вкладки риббона
            _metadataTabs = new RibbonContextTabs(ProjectExplorerRibbon);
            _metadataTabs.CaptionText = Resources.BI_PROJECTEXPLORER_RIBBON_CONTEXT_METADATA;
            _metadataTabs.FlashColor = Color.GreenYellow;            
            ObjectsListTab.SetOwningContext(_metadataTabs);
            ObjectActionsTab.SetOwningContext(_metadataTabs);
            ProjectExplorerRibbon.ContextTabs.Add(_metadataTabs);            
            _shortcutsTabs = new RibbonContextTabs(ProjectExplorerRibbon);
            _shortcutsTabs.CaptionText = Resources.BI_PROJECTEXPLORER_RIBBON_CONTEXT_SHORTCUT;
            _shortcutsTabs.FlashColor = Color.Pink;
            ShortcutTab.SetOwningContext(_shortcutsTabs);
            ProjectExplorerRibbon.ContextTabs.Add(_shortcutsTabs);
            _actionsetsTabs = new RibbonContextTabs(ProjectExplorerRibbon);
            _actionsetsTabs.CaptionText = Resources.BI_PROJECTEXPLORER_RIBBON_CONTEXT_ACTIONSET;
            _actionsetsTabs.FlashColor = Color.PaleVioletRed;
            ActionSetTab.SetOwningContext(_actionsetsTabs);
            ProjectExplorerRibbon.ContextTabs.Add(_actionsetsTabs);
            _dataTabs = new RibbonContextTabs(ProjectExplorerRibbon);
            _dataTabs.CaptionText = Resources.BI_PROJECTEXPLORER_RIBBON_CONTEXT_DATA;
            _dataTabs.FlashColor = Color.White;
            DataTab.SetOwningContext(_dataTabs);
            ProjectExplorerRibbon.ContextTabs.Add(_dataTabs);
            _situationsTabs = new RibbonContextTabs(ProjectExplorerRibbon);
            _situationsTabs.CaptionText = Resources.BI_PROJECTEXPLORER_RIBBON_CONTEXT_SITUATION;
            _situationsTabs.FlashColor = Color.LightBlue;
            SituationsTab.SetOwningContext(_situationsTabs);
            ProjectExplorerRibbon.ContextTabs.Add(_situationsTabs);
            //************************
            //загрузка настроек            
            _curSettings = new Settings();
            _curProjectSettings = new ProjectSettings(_projectLink);
            //теперь риббоны_preferencesForm = new PreferencesDialog(this);
            _settingsForm = new SettingsDialog(this);
            _curSettings.RestoreMe();
            Style = _curSettings.Style;
            //************************            
            SoundsPlayer = new SoundPlayer();
            SoundsPlayer.Stream = Resources.situation;
            SoundsPlayer.Load();
            int kindSelected = _curSettings.ProjectExplorerObjectsKindsSelectedIndex;
            if ((kindSelected >= 0) && (kindSelected < ObjectKindsView.Items.Count))
            {                
                foreach (ListViewItem item in ObjectKindsView.SelectedItems)
                {
                    item.Selected = false;
                }                
                ObjectKindsView.Items[kindSelected].Selected = true;                
            }
            SetTreeEnable(_curSettings.ProjectExplorerObjectsTreeEnabled);
            //////////////////
            _blockAccessToAppFolder = false;
            try
            {
                if (!Directory.Exists(Application.LocalUserAppDataPath))
                {
                    Directory.CreateDirectory(Application.LocalUserAppDataPath);
                }
            }
            catch (IOException)
            {
                GeneralMethods.ShowWarning(Resources.BI_PROJECTEXPLORER_ERROR_CANTCREATEFOLDERS);
                _blockAccessToAppFolder = true;
            }
            AutoOpen();                        
            ////////      
            int pageIndex = _curSettings.ProjectExplorerObjectsGroupsPageIndex;
            if ((pageIndex >= 0) && (pageIndex < ObjectsGroupTabControl.TabPages.Count) && (ObjectsGroupTabControl.TabPages[pageIndex].PageVisible))
            {
                ObjectsGroupTabControl.SelectedTabPageIndex = pageIndex;
            }
            int groupsWidth = _curSettings.ProjectExplorerObjectsGroupsWidth;
            if (groupsWidth > 0)
                ObjectsGroupTabControl.Width = groupsWidth;
            int objectPropertiesWidth = _curSettings.ProjectExplorerObjectPropertiesWidth;
            if (objectPropertiesWidth > 0)
                ObjectPropertiesArea.Width = objectPropertiesWidth;
            SetView(_curSettings.ProjectExplorerView);                 
            List<int> columnsWidth = _curSettings.ProjectExplorerColumnsWidth;
            for (int i = 0; i < columnsWidth.Count; i++)
            {
                if ((ObjectsList.Columns.Count > i) && (columnsWidth[i] > 0))
                {
                    ObjectsList.Columns[i].Width = columnsWidth[i];
                }
            }                        
            //***********
            _saveAbilityTimer = new Timer();
            _saveAbilityTimer.Interval = 1000;
            _saveAbilityTimer.Tick += new EventHandler(_saveAbilityTimer_Tick);
            _saveAbilityTimer.Start();
            ObjectsGroupTabControl.Focus();
            AutoOpenGroups();            
            //*****************
            _objectsHistory = new MetadataObjectsHistory();
            _historyFocus = -1;
            //подгрузка хинтов для видов объектов
            for (int i = 2; i < ObjectKindsView.Items.Count + 1; i++) //2 первых пропускаем, т.к. папки и None не выводим, а также последний пропускаем, т.к. это все объекты
            {
                ObjectKindsView.Items[i - 2].ToolTipText = ((MetadataObjectKind)i).GetObjectTip();
            }
            RefreshHints();                        
            UpdateRibbonMainItemsAbilities();
            UpdateAvailableActions();
            Status = Resources.BI_DONE;            
        }

        /// <summary>
        /// Возвращает/устанавливает флаг режима новичка
        /// </summary>
        public bool SimpleMode
        {
            get
            {
                return _curSettings.SimpleMode;
            }
            set
            {
                _curSettings.SimpleMode = value;
                RefreshHints();
            }
        }

        /// <summary>
        /// Подгрузка различных хинтов в соответсвии с настройками
        /// </summary>
        private void RefreshHints()
        {
            ObjectKindsView.ShowItemToolTips = SimpleMode;
        }

        /// <summary>
        /// Обрабатывает постановку фокуса в пустое поле описания объекта
        /// </summary>
        private void ProcessEnterEmptyDescription()
        {
            if (SelectedObjectDescriptionBox.Text.Equals(Resources.BI_PROJECTEXPLORER_ENTERDESCRIPTION))
            {
                SelectedObjectDescriptionBox.Text = string.Empty;
            }
        }

        /// <summary>
        /// Меняет описание объекта
        /// </summary>
        private bool ApplyDescriptionChange()
        {
            bool res = true;
            if ((string.IsNullOrEmpty(SelectedObjectDescriptionBox.Text)) || (SelectedObjectDescriptionBox.Text.Equals(Resources.BI_PROJECTEXPLORER_ENTERDESCRIPTION)))
            {
                SelectedObjectDescriptionBox.Text = Resources.BI_PROJECTEXPLORER_ENTERDESCRIPTION;
                SelectedObjectDescriptionBox.ForeColor = SystemColors.GrayText;                
                res = false;
            }
            else
            {
                SelectedObjectDescriptionBox.ForeColor = SystemColors.WindowText;
                ListView.SelectedListViewItemCollection sel = ObjectsList.SelectedItems;
                ListViewItem item = sel[0];
                IMetadataObjectDescriptor desc = item.Tag as IMetadataObjectDescriptor;                
                string newdescription = SelectedObjectDescriptionBox.Text;
                desc.SetDescription(newdescription);
                /*больше не надоDateTime newStamp = obj.TimeStamp;
                desc.Description = newdescription;                
                item.Tag = desc;*/                
            }
            RefreshObjects();
            _programFocusChange = true;
            ObjectsList.Focus();
            _programFocusChange = false;
            return res;
        }

        /// <summary>
        /// Обрабатывает смену отметки в области типов объектов
        /// </summary>
        private void ProcessObjectKindSelectionChange()
        {
            ActualizeInfoAboutObjectTypes();
            if (ObjectsList.SelectedIndices.Count == 0)
            {
                UpdateObjectProperties();
            }
            UpdateAvailableActions();
            UpdateAvailableHistoryActions();//чтобы при просмотре "Ситуаций" не было навигации по истории
        }

        /// <summary>
        /// Меняет внешний вид области объектов
        /// </summary>
        /// <param name="viewType"></param>
        private void SetView(ViewType viewType)
        {
            switch (viewType)
            {
                case ViewType.Short:
                    ObjectsList.View = View.LargeIcon;
                    break;
                case ViewType.Full:
                    ObjectsList.View = View.Details;
                    break;
            }
            _view = viewType;
            RefreshObjects();//чтобы картинки переподтянулись
            UpdateViewAbilities(false);
        }

        ///// <summary>
        ///// Переименовывает объект через поле имени в свойствах выделенного объекта
        ///// </summary>
        //private bool RenameObjectThroughNameBox(string newName)
        //{
        //    _programFocusChange = true;
        //    ObjectsList.Focus();
        //    _programFocusChange = false;
        //    if (EndObjectRenaming(ObjectsList.SelectedItems[0].Index, newName/*, true*/))
        //    {
        //        RefreshObjects();
        //        return true;
        //    }
        //    return false;
        //}

        /// <summary>
        /// Переходит на уровень выше
        /// </summary>
        private void FolderUp()
        {
            if (SelectedContainerId == _projectLink.RepositoryLink.RootFolder.Id)
                return;
            IMetadataObjectDescriptor owner = _projectLink.RepositoryLink.GetObjectDescriptorById(SelectedContainerId);            
            IMetadataObjectDescriptor parent = _projectLink.RepositoryLink.GetObjectDescriptorById(owner.ParentId);        
            FocusObject(parent, MetadataObjectsHistoryPointKind.OpenedContainerObject);
        }

        /// <summary>
        /// Обрабатывает нажатие клавиши в области объектов
        /// </summary>
        /// <param name="key"></param>
        private void ProcessObjectsListKeyDown(Keys key)
        {
            switch(key)
            {
                case Keys.Enter:
                    if (открытьToolStripMenuItem.Enabled)
                        OpenSelectedObject();
                    return;
                case Keys.Back:
                    FolderUp();
                    return;
                case Keys.F5:
                    RefreshAll();
                    return;
            }            
        }

        /// <summary>
        /// Меняем ярлык у объекта через поле ярлыка в свойствах выделенного объекта
        /// </summary>
        private void RelabelObject()
        {
            _programFocusChange = true;
            ObjectsList.Focus();
            _programFocusChange = false;
            if (EndObjectRelabeling(ObjectsList.SelectedItems[0].Index, SelectedObjectLabelBox.Text))
            {
                RefreshObjects();
            }
        }

        /// <summary>
        /// Конструктор формы
        /// </summary>        
        public ProjectExplorerForm()
        {
            _failedLogon = false;
            _canceledLogon = false;
            ReadUsers();
            if (_usersList.CurrentUser != null)
            {
                GeneralMethods.ShowInformation(UsersSharedMethods.FirstLogOnInformation);
                UserPasswordChangeDialog cpd = new UserPasswordChangeDialog(false, _usersList.CurrentUser);
                cpd.ShowDialog();
            }
            else
            {
                LogOnDialog ld = new LogOnDialog(_usersList);
                DialogResult result = ld.ShowDialog();
                switch (result)
                {
                    case DialogResult.Abort:
                        Trace.StartBlock("authorization");
                        Trace.Message("FAILED");
                        Trace.EndBlock();
#if DEBUG
                        break;
#else
                        _failedLogon = true;
                        Close();
                        return;
#endif
                    case DialogResult.Cancel:
                        Trace.StartBlock("authorization");
                        Trace.Message("CANCELED");
                        Trace.EndBlock();
                        _canceledLogon = true;
                        Close();
                        return;
                }
            }
            _aboutProgramDialog = new AboutDialog();
            RapidAnalysisWindows = new List<RapidAnalysisForm>();
            InitializeComponent();
        }

        private void MetadataViewerForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            _systemDB.Save(Application.LocalUserAppDataPath + "\\" + SystemDBProvider.FileName);
            if ((!_failedLogon) && (!_canceledLogon))
            {
                e.Cancel = !AskBeforeClosing();
            }
            if (!e.Cancel)
            {
                Status = Resources.BI_PROGRAM_CLOSING;
            }
        }

        private void ProjectExplorerForm_Load(object sender, EventArgs e)
        {
            ProcessProgramStarted();
        }

        private void создатьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            /*теперь риббоныif (создатьToolStripMenuItem.DropDownItems.Count == 0)
            {
                ShowCreateObjectDialog();
            }*/
        }

        private void создатьНовыйОбъектToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (создатьНовыйОбъектToolStripMenuItem.DropDownItems.Count == 0)
            {
                ShowCreateObjectDialog();
            }
        }

        private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowDeleteObjectDialog();
        }

        private void удалитьToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DeleteSelectedObjects();
        }

        private void ObjectsList_ContextMenu_Opening(object sender, CancelEventArgs e)
        {
            bool isTreeCall = UpdateAvailableActions();
            UpdateViewAbilities(isTreeCall);
        }

        private void объектToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
        {
            UpdateAvailableActions();
        }

        private void переименоватьToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //теперь риббоныStartObjectRenaming();
        }

        private void переименоватьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StartObjectRenaming();
        }

        private void ObjectsList_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {            
            e.CancelEdit = !EndObjectRenaming(e.Item, e.Label);
            if (!e.CancelEdit)
                UpdateObjectProperties();
            _inObjectF2Renaming = false;
            UpdateAvailableActions();
        }

        private void открытьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenSelectedObject();
        }

        private void открытьToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //теперь риббоныOpenSelectedObject();
        }

        private void ObjectsList_DoubleClick(object sender, EventArgs e)
        {
            OpenSelectedObject();
        }

        private void ObjectsList_KeyDown(object sender, KeyEventArgs e)
        {
            ProcessObjectsListKeyDown(e.KeyCode);            
        }

        /// <summary>
        /// Обрабатывает тик таймера смены выделения объектов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _objectsSelectionTimer_Tick(object sender, EventArgs e)
        {
            _objectsSelectionTimer.Stop();
            _objectsSelectionTimer.Dispose();
            _objectsSelectionTimer = null;            
            bool wasMany = _beforeSelectedObjectsIds.Count > 1;
            bool wasNo = _beforeSelectedObjectsIds.Count == 0;
            foreach (ListViewItem item in ObjectsList.Items)
            {
                MetadataObjectDescriptor info = (MetadataObjectDescriptor)item.Tag;
                if (item.Selected)
                {
                    if (!_beforeSelectedObjectsIds.Contains(info.Id))
                    {
                        _beforeSelectedObjectsIds.Add(info.Id);
                    }
                }
                else
                {
                    if (_beforeSelectedObjectsIds.Contains(info.Id))
                    {
                        _beforeSelectedObjectsIds.Remove(info.Id);
                    }
                }
            }
            /*вроде больше не нужно, раз есть таймер
            //муть, чтобы убрать мигания, например, при снятии выделения с объектов                
            if (wasNo && _beforeSelectedObjectsIds.Count == 0)
                return; //ниче не поменялось
            if (wasMany && _beforeSelectedObjectsIds.Count > 1)
                return; //ниче не поменялось                                
            if (wasMany && _beforeSelectedObjectsIds.Count == 1)
            {
                ///а вот тут ситуация посложнее:
                ///быть может мы вместо 10 выделили 1 объект,
                ///а быть может это мы снимаем выделение со всех 10 объектов;
                ///в первом случае свойства объекта отобразить надо
                ///а во втором случае отображать их не надо, потому что все равно
                ///в итоге будет ноль выделенных объектов                    
                ///
                ///как обойти - не придумал...                                                           
            }*/
            //работаем
            UpdateObjectProperties();
            UpdateAvailableActions(); 
        }

        /// <summary>
        /// Обрабатывает смену выделения в области объектов
        /// </summary>
        private void ProcessObjectsListSelectionChange()
        {
            if (_programFocusChange)
                return;           
            //срабатываем только когда выделение перестало колбаситься, обождав полсекунды
            if (_objectsSelectionTimer != null)
            {
                _objectsSelectionTimer.Stop();
                _objectsSelectionTimer.Dispose();
                _objectsSelectionTimer = null;
            }
            _objectsSelectionTimer = new Timer();
            _objectsSelectionTimer.Interval = 500;
            _objectsSelectionTimer.Enabled = true;
            _objectsSelectionTimer.Tick += new EventHandler(_objectsSelectionTimer_Tick);
            _objectsSelectionTimer.Start();                       
        }

        private void ObjectsList_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {               
            ProcessObjectsListSelectionChange();
        }

        private void SelectedObjectLabelBox_Leave(object sender, EventArgs e)
        {
            if (_programFocusChange)
                return;
            RelabelObject();            
        }

        private void SelectedObjectLabelBox_KeyDown(object sender, KeyEventArgs e)
        {
            switch(e.KeyCode)
            {
                case Keys.Enter:
                    RelabelObject();
                    break;
            }            
        }

        private void краткаяИнформацияToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //теперь риббоныSetView(ViewType.Short);
        }

        private void подробнаяИнформацияToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //теперь риббоныSetView(ViewType.Full);
        }

        private void краткаяИнформацияToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetView(ViewType.Short);
        }

        private void подробнаяИнформацияToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetView(ViewType.Full);
        }

        private void видToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
        {
            //теперь риббоныUpdateViewAbilities(false);
        }

        private void импортироватьДанныеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowDataExtractionDialog(true);
        }

        private void импортироватьДанныеToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            //теперь риббоны ImportData();         
        }

        private void SelectedObjectDescriptionBox_Enter(object sender, EventArgs e)
        {
            ProcessEnterEmptyDescription();
        }

        private void SelectedObjectDescriptionBox_Leave(object sender, EventArgs e)
        {
            if (_programFocusChange)
                return;
            ApplyDescriptionChange();            
        }

        private void SelectedObjectDescriptionBox_KeyDown(object sender, KeyEventArgs e)
        {
            switch(e.KeyCode)
            {
                case Keys.Enter:
                    if (ApplyDescriptionChange())
                        break;
                    e.SuppressKeyPress = true;                    
                    break;
            }                                        
        }

        private void закрытьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //риббоны теперьClose();
        }

        private void оПрограммеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowAboutDialog();
        }

        /// <summary>
        /// Скрывает/показывает панель выбора отображаемых объектов
        /// </summary>
        private void ToggleObjectsGroups()
        {
            ObjectsGroupTabControl.Visible = !ObjectsGroupTabControl.Visible;
            UpdateViewAbilities(false);
        }

        /// <summary>
        /// Скрывает/показывает свойства объекта
        /// </summary>
        private void ToggleObjectProperties()
        {
            ObjectPropertiesArea.Visible = !ObjectPropertiesArea.Visible;
            /*if (ObjectPropertiesArea.Visible)
                UpdateObjectProperties();*/            
            _handheldPropertiesClose = !ObjectPropertiesArea.Visible;
            UpdateViewAbilities(false);
        }

        private void ShowOrHideSplitterMenuItem_Click(object sender, EventArgs e)
        {
            ToggleObjectsGroups();
        }

        private void ShowOrHideSplitter2MenuItem_Click(object sender, EventArgs e)
        {
            ToggleObjectProperties();
        }

        /// <summary>
        /// Отображение окна среды разработки
        /// </summary>
        public void ShowIDEWindow()
        {
            if (_IDEWindow == null)
            {
                _IDEWindow = new IDEForm(this);
                _IDEWindow.Show();
            }
            else
            {
                _IDEWindow.Focus();
            }
        }

        /// <summary>
        /// Открытие указанного свода действий и, если надо, среды разработки
        /// </summary>
        public void ShowIDEWindow(IActionSet actionSet)
        {
            ShowIDEWindow();
            _IDEWindow.AddActionSetWindow(actionSet);
        }

        /// <summary>
        /// Обновляет заголовок окна свода действий, если оно открыто
        /// </summary>
        public void UpdateActionSetWindowCaption(IActionSet actionSet)
        {
            if (_IDEWindow == null)
                return;
            _IDEWindow.UpdateActionSetWindowCaption(actionSet);            
        }

        /// <summary>
        /// Закрывает окно свода действий, если оно открыто
        /// </summary>
        public bool CloseActionSetWindow(IActionSet actionSet)
        {
            if (_IDEWindow == null)
                return true;
            return _IDEWindow.CloseActionSetWindow(actionSet);            
        }

        /// <summary>
        /// Отображение окна системы документооборота
        /// </summary>
        public void ShowWorkflowWindow()
        {
            if (_workflowWindow == null)
            {
                _workflowWindow = new WorkflowForm(this);
                _workflowWindow.Show();
                return;
            }
            _workflowWindow.Focus();            
        }

        private void обсуждениеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowWorkflowWindow();
        }

        /// <summary>
        /// Вызывает диалог извлечения данных в указанный объект репозитория
        /// </summary>
        public void ShowDataExtractionDialog(IMetadataObjectDescriptor desc)
        {
            bool objectNotSelected = false;
            if (desc == null)
            {
                objectNotSelected = true;
                if (ProjectLink.RepositoryLink.ObjectsCount(MetadataObjectKind.Table) == 0)
                {
                    GeneralMethods.ShowUserError(Resources.BI_LOADDATA_ERROR_TABLE_NOTFOUNDANYONE);
                    return;
                }
            }
            OpenFileDialogExcel.InitialDirectory = Application.LocalUserAppDataPath;
            OpenFileDialogExcel.FileName = string.Empty;
            if (OpenFileDialogExcel.ShowDialog() == DialogResult.OK)
            {
                string fname = OpenFileDialogExcel.FileName;
                IMetadataObject objectForImport = null;
                if (!objectNotSelected)
                    objectForImport = ProjectLink.RepositoryLink.GetObjectDescriptorById(desc.Id).Bind();
                DataExtractionDialog ldata = new DataExtractionDialog(ProjectLink, fname, objectForImport);
                ldata.ShowDialog();
                UpdateObjectProperties();
            }
        }

        /// <summary>
        /// Вызывает диалог извлечения данных в произвольный объект репозитория
        /// </summary>
        public void ShowDataExtractionDialog()
        {
            ShowDataExtractionDialog(null);
        }

        private void импортДанныхToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоны LoadData();
        }

        /*/// <summary>
        /// Создает регламентный отчет
        /// </summary>
        /// <param name="kind"></param>
        private void MakeProceduralReport(ICube cube, ProceduralReportKind kind)
        {            
            ProceduralReport report = null;
            //строим отчет
            try
            {
                report = new ProceduralReport(this, cube, kind);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.RS_ERROR_USER_CAPTION, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            report = null;
        }*/

        private void динамикаОборотаОбщественногоПитанияПоРосстатуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //TODO
            //bbbMakeProceduralReport(Metadata.metadata.GetCubeByIndex(0), ProceduralReportKind.DynamicsOfTrafficOnCateringByRosStat);
        }

        /*теперь риббоны/// <summary>
        /// Отображение диалога "Оформление"
        /// </summary>
        private void ShowPreferences()
        {
            _preferencesForm.ShowDialog();
            MainFormLink.HierarchyForm.RefreshMap();
        }*/

        private void оформлениеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowPreferences();
        }

        private void splitter2_DoubleClick(object sender, EventArgs e)
        {
            ToggleObjectProperties();
        }

        private void newProjectToolStripButton_Click(object sender, EventArgs e)
        {
            ShowCreateProjectDialog();
        }

        private void openProjectToolStripButton_Click(object sender, EventArgs e)
        {
            ShowOpenProjectDialog();
        }

        private void saveProjectToolStripButton_Click(object sender, EventArgs e)
        {
            SaveProject();
        }

        private void СоздатьПроектToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowCreateProjectDialog();
        }

        private void ОткрытьПроектToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowOpenProjectDialog();
        }

        private void СохранитьПроектToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныSaveProject();
        }

        private void СохранитьПроектКакToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowSaveProjectAsDialog();
        }

        private void ObjectPropertiesSplitter_SplitterMoved(object sender, SplitterEventArgs e)
        {
            _curSettings.ProjectExplorerObjectPropertiesWidth = ObjectPropertiesArea.Width;
        }

        private void средаРазработкиToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowIDEWindow();
        }

        private void иерархияСитуацийToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоны(УШЛО В НИКУДА,Т.К.В БУДУЩЕМ ВСЕ РАВНО УБЕРУ)MainFormLink.Focus();
        }

        /// <summary>
        /// Отображение диалога "Настройки"
        /// </summary>
        private void ShowSettings()
        {
            _settingsForm.ShowDialog();            
        }

        private void настройкиToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowSettings();
        }

        /// <summary>
        /// Отображает диалог поиска объекта метаданных
        /// </summary>
        private void ShowFindObjectDialog()
        {
            (new FindObjectDialog(this, VisibleTypes)).ShowDialog();
        }

        private void SearchToolStripButton_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowFindObjectDialog();
        }

        private void найтиToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowFindObjectDialog();
        }

        private void найтиToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ShowFindObjectDialog();
        }

        private void ObjectKindsView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (_programKindChange)
                return;
            if (e.IsSelected)
            {
                ProcessObjectKindSelectionChange();
            }            
        }

        private void KindsSplitter_SplitterMoved(object sender, SplitterEventArgs e)
        {
            _curSettings.ProjectExplorerObjectsGroupsWidth = ObjectsGroupTabControl.Width;
        }

        private void KindsSplitter_DoubleClick(object sender, EventArgs e)
        {
            ToggleObjectsGroups();
        }

        /// <summary>
        /// Автооткрытие панели выбора отображаемых объектов
        /// </summary>
        private void AutoOpenGroups()
        {
            if (_curSettings.AutohideObjectsGroups && !ObjectsGroupTabControl.Visible)
            {
                ToggleObjectsGroups();
            }
        }

        /// <summary>
        /// Автоскрытие панели выбора отображаемых объектов
        /// </summary>
        private void AutoCloseGroups()
        {
            if (_curSettings.AutohideObjectsGroups && !ObjectsGroupTabControl.Focused && !ObjectKindsView.Focused && !ObjectsTree.Focused && ObjectsGroupTabControl.Visible)
                ToggleObjectsGroups();
        }

        private void KindsSplitter_MouseHover(object sender, EventArgs e)
        {
            AutoOpenGroups();
        }

        private void ObjectsList_MouseHover(object sender, EventArgs e)
        {
            AutoCloseGroups();
        }

        private void ObjectsList_Enter(object sender, EventArgs e)
        {
            AutoCloseGroups();
            UpdateAvailableActions();//хотя бы для того, чтоб Ctrl+A работал и без установки выделения на итем
        }

        private void ObjectsTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            _selectedContainerId = ((MetadataObjectDescriptor)e.Node.Tag).Id;
            _beforeSelectedObjectsIds = new List<Guid>();
            RefreshObjects();            
            UpdateAvailableActions();
            UpdateObjectProperties();
        }

        private void ObjectsTree_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {            
            if (e.Label == null)
            {
                //отменили переименование через Escape
                return;
            }
            IMetadataObjectDescriptor desc = e.Node.Tag as IMetadataObjectDescriptor;
            if (desc.Id == _projectLink.RepositoryLink.RootFolder.Id)
            {
                //это пытаются переименовать название проекта
                e.CancelEdit = true;
                return;
            }
            try
            {
                desc.SetName(e.Label);
            }
            catch (BIMetadataObjectEmptyNameException ex)
            {
                GeneralMethods.ShowUserError(ex.Message);
                e.CancelEdit = true;
                return;
            }
            PathBox.Text = e.Node.FullPath.Substring(0, e.Node.FullPath.LastIndexOf(e.Node.Text)) + e.Label;
            _inObjectF2Renaming = false;
            UpdateAvailableActions();
        }

        /// <summary>
        /// Обрабатывает раскрытие/закрытие контейнерного объекта в дереве контейнерных объектов
        /// </summary>
        /// <param name="node"></param>
        /// <param name="isExpanded"></param>
        private void ProcessContainerExpand(TreeNode node, bool isExpanded)
        {
            node.ImageKey = MetadataObjectKind.Folder.GetImageKey(MetadataObjectImageSize.Small, isExpanded ? MetadataObjectState.Expanded : MetadataObjectState.Normal);
            node.SelectedImageKey = node.ImageKey;            
            if (_programTreeBuild)
                return;
            MetadataObjectDescriptor info = (MetadataObjectDescriptor)node.Tag;
            if (_treeExpanded.Contains(info.Id) && !isExpanded)
            {
                _treeExpanded.Remove(info.Id);
            }
            if (!_treeExpanded.Contains(info.Id) && isExpanded)
            {
                _treeExpanded.Add(info.Id);                
            }
        }

        private void ObjectsTree_AfterExpand(object sender, TreeViewEventArgs e)
        {
            ProcessContainerExpand(e.Node, true);            
        }

        private void ObjectsTree_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            ProcessContainerExpand(e.Node, false);            
        }

        /// <summary>
        /// Возвращает флаг доступности дерева контейнерных объектов
        /// </summary>
        private bool IsTreeEnabled
        {
            get
            {
                return EnableObjectsTreeButton.State.HasFlag(RibbonItemChangedStates.Checked);
            }
        }

        /// <summary>
        /// Обновляет видимость дерева объектов проекта
        /// </summary>
        private void UpdateTreeVisible()
        {
            bool justShowed = !ObjectsTree.Visible && IsTreeEnabled;
            ObjectsTree.Visible = IsTreeEnabled;
            PathBox.Visible = IsTreeEnabled;
            RefreshObjects();            
            if (justShowed)
                ObjectsGroupTabControl.SelectedTabPage = ObjectsTreeTab;
        }

        private void создатьНовуюПапкуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныShowCreateObjectDialog(MetadataObjectKind.Folder);
        }

        private void создатьНовуюПапкуToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Folder);
        }

        private void ObjectsTree_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            ObjectsTree.SelectedNode = e.Node;
        }

        /// <summary>
        /// Рекурсивно выключает визуальное состояние вырезки в дереве контейнерных объектов
        /// </summary>
        /// <param name="topNode"></param>
        private void DisableTreeCut(TreeNode topNode)
        {
            foreach (TreeNode node in topNode.Nodes)
            {
                if (_cuttedItemsDescriptors.Contains((MetadataObjectDescriptor)node.Tag))
                {
                    node.ForeColor = SystemColors.WindowText;
                }
                DisableTreeCut(node);
            }            
        }

        /// <summary>
        /// Выключает состояние вырезки
        /// </summary>
        private void DisableCuts()
        {
            foreach (ListViewItem item in ObjectsList.Items)
            {
                if (_cuttedItemsDescriptors.Contains((MetadataObjectDescriptor)item.Tag))
                {
                    item.ForeColor = SystemColors.WindowText;
                }
            }
            DisableTreeCut(ObjectsTree.Nodes[0]);            
            _cuttedItemsDescriptors.Clear();
            _cutOperation = false;
        }

        /// <summary>
        /// Запоминает объекты для копирования/вырезки
        /// </summary>        
        private void RememberObjects(bool toCut)
        {
            DisableCuts();
            Clipboard.Clear();
            _cutOperation = toCut;
            if (ObjectsTree.Focused)
            {
                //копируем из дерева контейнерных объектов
                TreeNode node = ObjectsTree.SelectedNode;
                IMetadataObjectDescriptor desc = node.Tag as IMetadataObjectDescriptor;
                DataObject dobj = new DataObject();
                dobj.SetData(desc.Id);
                Clipboard.SetDataObject(dobj);
                if (toCut)
                {
                    _cuttedItemsDescriptors.Add(desc);                    
                    node.ForeColor = SystemColors.GrayText;
                }
            }
            else
            {
                int c = ObjectsList.SelectedItems.Count;
                Guid[] ids = new Guid[c];
                //копируем из области объектов                
                for (int i = 0; i < c; i++)
                {
                    ListViewItem item = ObjectsList.SelectedItems[i];
                    IMetadataObjectDescriptor desc = item.Tag as IMetadataObjectDescriptor;
                    ids[i] = desc.Id;
                    if (toCut)
                    {
                        _cuttedItemsDescriptors.Add(desc);                        
                        item.ForeColor = SystemColors.GrayText;
                    }
                }
                DataObject dobj = new DataObject();
                dobj.SetData(ids);
                Clipboard.SetDataObject(dobj);
            }
            UpdateAvailableActions();//хотя бы для того, чтоб доступности опирации копи-паст у риббона обновились
        }

        /// <summary>
        /// Копирует объекты
        /// </summary>
        private void CopyObjects()
        {
            RememberObjects(false);
        }

        /// <summary>
        /// Вырезает объекты
        /// </summary>
        private void CutObjects()
        {
            RememberObjects(true);
        }

        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныCutObjects();
        }

        /// <summary>
        /// Выделяет все объекты в области объектов
        /// </summary>
        private void SelectAllObjects()
        {
            _programFocusChange = true;
            ObjectsList.Focus();
            int c = ObjectsList.Items.Count;
            for (int i = 0; i < c; i++)
            {
                ListViewItem item = ObjectsList.Items[i];
                if (i == c - 1)
                    _programFocusChange = false;
                item.Selected = true;
            }
            _programFocusChange = false;
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныSelectAllObjects();
        }

        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныCopyObjects();
        }

        /// <summary>
        /// Вставляет объекты
        /// </summary>
        private void PasteObjects(IContainerMetadataObject destination)
        {             
            IDataObject dataobj = Clipboard.GetDataObject();
            Guid[] ids = null;
            if (dataobj.GetDataPresent(typeof(Guid)))
            {
                ids = new Guid[1];
                ids[0] = (Guid)dataobj.GetData(typeof(Guid));
            }
            else
            {
                if (dataobj.GetDataPresent(typeof(Guid[])))
                {
                    object keeped = dataobj.GetData(typeof(Guid[]));
                    ids = (Guid[])keeped;
                }
                else
                {
                    Assert.Fail(Assert.Id.Assert00126);
                }
            }            
            int c = ids.Length;
            int i = 0;
            foreach (Guid id in ids)
            {
                i++;
                IMetadataObject sourceObject = _projectLink.RepositoryLink.GetObjectDescriptorById(id).Bind();
                if (sourceObject == null)
                {
                    //удалили уже видать скопированный/вырезанный объект
                    GeneralMethods.ShowUserError(string.Format(Resources.BI_PROJECTEXPLORER_OBJECTNOTFOUND, string.Empty));
                    continue;
                }
                Status = string.Format(
                    _cutOperation ? Resources.BI_PROJECTEXPLORER_OPERATION_CUT : Resources.BI_PROJECTEXPLORER_OPERATION_COPY,
                    sourceObject.ToString(), i.ToString(), c.ToString());
                try
                {
                    if (_cutOperation)
                    {
                        sourceObject.SetParentContainer(destination);
                    }
                    else
                    {
                        sourceObject.CloneTo(destination);
                    }
                }
                catch (BIMetadataObjectWrongParentException ex)
                {
                    GeneralMethods.ShowUserError(ex.Message);
                    break;
                }
            }
            Status = Resources.BI_DONE;
            if (_cutOperation)
            {
                DisableCuts();
                Clipboard.Clear();
            }
            RefreshTree();
            RefreshObjects();
        }

        /// <summary>
        /// Вставляет объекты в текущую папку
        /// </summary>
        private void PasteObjects()
        {
            PasteObjects(_projectLink.RepositoryLink.GetObjectDescriptorById(SelectedContainerId).Bind() as IContainerMetadataObject);
        }

        /// <summary>
        /// Обновляет список всех объектов и дерево объектов
        /// </summary>
        private void RefreshAll()
        {
            bool haveRowItems = _view == ViewType.Full;
            ListViewItem topItem = null;
            int topItemIndex = -1;
            if (haveRowItems)
            {
                topItem = ObjectsList.TopItem;
                if (topItem == null)
                    haveRowItems = false;
                else
                    topItemIndex = topItem.Index;
            }
            var selectedObjects = _beforeSelectedObjectsIds; //надо запомнить, потому что сбросятся после RefreshTree
            RefreshTree();
            _beforeSelectedObjectsIds = selectedObjects;
            RefreshObjects();
            UpdateObjectProperties();
            if (haveRowItems && (ObjectsList.Items.Count > topItemIndex))
            {
                ///не катит так просто: ObjectsList.TopItem = ObjectsList.Items[topItemIndex];
                ///поэтому тупой обход баги .NET'а,
                ///описанный здесь - http://www.codeguru.com/forum/archive/index.php/t-412218.html
                ///и здесь внизу - http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.topitem.aspx                
                ListViewItem needTopItem = ObjectsList.Items[topItemIndex];
                while (ObjectsList.TopItem.Index != topItemIndex)
                {
                    ObjectsList.TopItem = needTopItem;
                    System.Threading.Thread.Sleep(10);
                }
            }
        }

        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
           //теперь риббоныPasteObjects();
        }

        private void CutContextMenuItem_Click(object sender, EventArgs e)
        {
            CutObjects();
        }

        private void CopyContextMenuItem_Click(object sender, EventArgs e)
        {
            CopyObjects();
        }

        private void PasteContextMenuItem_Click(object sender, EventArgs e)
        {
            PasteObjects();
        }

        private void SelectAllContextMenuItem_Click(object sender, EventArgs e)
        {
            SelectAllObjects();
        }

        private void FolderUpButton_Click(object sender, EventArgs e)
        {
            //теперь риббоныFolderUp();
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            //теперь риббоныRefreshAll();
        }

        private void наУровеньВышеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныFolderUp();
        }

        private void обновитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныRefreshAll();
        }

        private void ObjectKindsView_Enter(object sender, EventArgs e)
        {
            UpdateAvailableActions();
        }

        private void ObjectsTree_Enter(object sender, EventArgs e)
        {
            UpdateAvailableActions();
        }

        /// <summary>
        /// Переходит по истории с заданным смещением
        /// </summary>
        private void HistoryGo(int offset, Directions1D direction)
        {
            Func<int, int> incrementer = x => direction == Directions1D.Back ? x - 1 - offset : x + 1 + offset;
            int beforeFocus = _historyFocus;
            _historyFocus = incrementer(_historyFocus);
            bool failed = false;
            if ((_historyFocus < 0) || (_historyFocus >= _objectsHistory.Count)) //бывает когда перешли по истории и, не дождавшись обновления панели свойств объекта, пытаемся перейти еще по истории
                failed = true;
            failed = failed || !FocusObject(_objectsHistory[_historyFocus]);
            if (failed)
                _historyFocus = beforeFocus;
        }

        /// <summary>
        /// Переходит по истории
        /// </summary>
        private void HistoryGo(Directions1D direction)
        {
            HistoryGo(0, direction);
        }

        private void перейтиНазадToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныHistoryGo(Directions1D.Back);
        }

        private void перейтиВпередToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныHistoryGo(Directions1D.Forward);
        }

        private void HistoryBackButton_ButtonClick(object sender, EventArgs e)
        {
            //теперь риббоныHistoryGo(Directions1D.Back);
        }

        private void HistoryForwardButton_ButtonClick(object sender, EventArgs e)
        {
            //теперь риббоныHistoryGo(Directions1D.Forward);
        }        

        private void ObjectPropertiesArea_OnEditableGroupBoxCaptionChanging(string newCaption, ref CancelEventArgs args)
        {                        
            if (!EndObjectRenaming(ObjectsList.SelectedItems[0].Index, newCaption))
                args.Cancel = true;                         
        }

        private void ObjectPropertiesArea_OnEditableGroupBoxCaptionBeforeEdit()
        {
            ObjectPropertiesArea.Text = ((MetadataObjectDescriptor)ObjectsList.SelectedItems[0].Tag).Name;
        }

        private void ObjectPropertiesArea_OnEditableGroupBoxCaptionAfterEdit()
        {
            RefreshObjects();
            UpdateObjectPropertiesCaption();
        }

        private void объектыТолькоИзВыбраннойПапкиToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныEnableTreeCheck.Checked = объектыТолькоИзВыбраннойПапкиToolStripMenuItem.Checked;
        }

        private void объектыТолькоИзВыбраннойПапкиToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ToggleTreeEnable();            
        }        

        /*/// <summary>
        /// Отображает виды объектов в меню
        /// </summary>
        private void FillObjectKindsInMenu()
        {
            ToolStripItemCollection items = видыОбъектовToolStripMenuItem.DropDownItems;
            items.Clear();
            ListView.ListViewItemCollection originalItems = ObjectKindsView.Items;
            for (int i = 0; i < originalItems.Count; i++)
            {
                ToolStripItem newItem = items.Add(originalItems[i].Text);
                if (originalItems[i].Selected)
                    (newItem as ToolStripMenuItem).Checked = true;
                newItem.Image = originalItems[i].ImageList.Images[originalItems[i].ImageKey];
                newItem.Click += new EventHandler(kindMenuItem_Click);
            }
        }*/

        private void свойстваToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToggleObjectProperties();
            UpdateObjectProperties();
        }

        private void свойстваToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            /*теперь риббоныToggleObjectProperties();
            UpdateObjectProperties();*/
        }

        /// <summary>
        /// Создает ссылку на выделенный объект
        /// </summary>
        private void AttachShortcut()
        {
            if (ObjectsTree.Focused)
            {
                SelectedContainerId = ((MetadataObjectDescriptor)ObjectsTree.SelectedNode.Tag).Id;
                return;
            }
            ListView.SelectedListViewItemCollection sel = ObjectsList.SelectedItems;
            if (sel.Count != 1)
            {
                Assert.Fail(Assert.Id.Assert00127);
                return;
            }
            ListViewItem item = sel[0];
            IMetadataObjectDescriptor desc = item.Tag as IMetadataObjectDescriptor;
            IShortcut shortcut = _projectLink.RepositoryLink.CreateObject(
                MetadataObjectKind.Shortcut,
                desc.Name,
                _projectLink.RepositoryLink.ProposeNewObjectLabel(Resources.BI_PROJECTEXPLORER_SHORTCUT_PREFIX + desc.Label),
                string.Empty,
                _projectLink.RepositoryLink.GetObjectDescriptorById(desc.ParentId)).Bind() as IShortcut;            
            shortcut.SetAim(desc);
            if (VisibleTypes.All || (VisibleTypes.Kind == MetadataObjectKind.Shortcut))
            {
                RefreshObjects();
                FocusObject(shortcut.Descriptor);
            }
            else
                GeneralMethods.ShowInformation(string.Format(Resources.BI_PROJECTEXPLORER_SHORTCUT_INVISIBLE, desc.ToString(), shortcut.ToString()));
        }

        /// <summary>
        /// Переходит к целевому объекту выделенной Ссылки
        /// </summary>
        private void GoToShortcutAim()
        {
            ListView.SelectedListViewItemCollection sel = ObjectsList.SelectedItems;
            if (sel.Count != 1)
            {
                Assert.Fail(Assert.Id.Assert00128);
                return;
            }
            ListViewItem item = sel[0];
            IMetadataObjectDescriptor desc = item.Tag as IMetadataObjectDescriptor;
            IShortcut shortcut = desc.Bind() as IShortcut;
            object aim = shortcut.GetAim();
            if (aim == null)
            {
                GeneralMethods.ShowUserError(string.Format(Resources.BI_PROJECTEXPLORER_SHORTCUT_NOAIM, desc.ToString()));
                return;
            }
            switch(shortcut.GetShortcutType())
            {
                case ShortcutType.None:
                    Assert.Fail(Assert.Id.Assert00129); //тогда и цель должна была быть null
                    break;
                case ShortcutType.MetadataObject:
                    MetadataObjectDescriptor aimObject = (MetadataObjectDescriptor)aim;
                    FocusObject(aimObject);
                    break;
                default:
                    Assert.Fail(Assert.Id.Assert00121);
                    break;
            }
        }

        private void создатьСсылкуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныCreateShortcut();
        }

        private void создатьСсылкуToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            AttachShortcut();
        }        

        private void перейтиКОбъектуToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //теперь риббоныGoToShortcutAim();
        }

        private void перейтиКОбъектуToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            GoToShortcutAim();
        }

        private void QuitProjectExplorer_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void CreateProjectItem_Click(object sender, EventArgs e)
        {
            ShowCreateProjectDialog();
        }

        private void OpenProjectItem_Click(object sender, EventArgs e)
        {
            ShowOpenProjectDialog();
        }

        private void SaveProjectItem_Click(object sender, EventArgs e)
        {
            SaveProject();
        }

        private void SaveProjectAsItem_Click(object sender, EventArgs e)
        {
            ShowSaveProjectAsDialog();
        }

        private void OpenWorkflowItem_Click(object sender, EventArgs e)
        {
            ShowWorkflowWindow();
        }

        private void FastSaveButton_Click(object sender, EventArgs e)
        {
            SaveProject();
        }

        private void CopyButton_Click(object sender, EventArgs e)
        {
            CopyObjects();
        }

        private void CutButton_Click(object sender, EventArgs e)
        {
            CutObjects();
        }

        private void PasteButton_Click(object sender, EventArgs e)
        {
            PasteObjects();
        }

        private void VisibleObjectsPanel_ButtonMoreClick(object sender, EventArgs e)
        {
            if (!ObjectsGroupTabControl.Visible)
                ToggleObjectsGroups();
            else
                ObjectsGroupTabControl.Focus();
        }

        /// <summary>
        /// Устанавливает режим отображения объектов по типам / по типам и папкам
        /// </summary>
        private void SetTreeEnable(bool isEnable)
        {
            if (VisibleTypes.Kind == MetadataObjectKind.Situation)
            {
                isEnable = false;                
            }            
            DisableObjectsTreeButton.SetState(isEnable ? DisableObjectsTreeButton.State & ~RibbonItemChangedStates.Checked : DisableObjectsTreeButton.State | RibbonItemChangedStates.Checked);
            EnableObjectsTreeButton.SetState(!isEnable ? EnableObjectsTreeButton.State & ~RibbonItemChangedStates.Checked : EnableObjectsTreeButton.State | RibbonItemChangedStates.Checked);
            объектыТолькоИзВыбраннойПапкиToolStripMenuItem1.Checked = isEnable;
            ObjectsTreeTab.PageVisible = isEnable;
            PathBox.Visible = isEnable;
            UpdateTreeVisible();
        }

        /// <summary>
        /// Переключает режим отображения объектов по типам / по типам и папкам
        /// </summary>
        private void ToggleTreeEnable()
        {
            SetTreeEnable(!IsTreeEnabled);
        }

        private void DisableObjectsTreeButton_Click(object sender, EventArgs e)
        {
            SetTreeEnable(false);
        }

        private void EnableObjectsTreeButton_Click(object sender, EventArgs e)
        {
            SetTreeEnable(true);
        }

        /*/// <summary>
        /// Обрабатывает клик по виду объектов в меню
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void kindMenuItem_Click(object sender, EventArgs args)
        {
            ToolStripItem item = sender as ToolStripItem;
            var _beforeSelectedPage = ObjectsGroupTabControl.SelectedTabPage;
            ObjectKindsView.Items[item.Owner.Items.IndexOf(item)].Selected = true;
            if (_beforeSelectedPage.PageVisible)
                ObjectsGroupTabControl.SelectedTabPage = _beforeSelectedPage;
        }*/

        /// <summary>
        /// Обрабатывает клик по виду объектов в риббоне
        /// </summary>        
        private void ObjectKindRibbonClick(object sender)
        {
            var button = sender as RibbonButton;
            var _beforeSelectedPage = ObjectsGroupTabControl.SelectedTabPage;
            int index = -1;
            foreach (RibbonItem item in ViewTypesButtonsList.ButtonsCollection)
            {
                if (item.Text == button.Text)
                {
                    index = ViewTypesButtonsList.ButtonsCollection.IndexOf(item);
                    break;
                }
            }
            Assert.FailIf(index == -1, Assert.Id.Assert00246);
            ObjectKindsView.Items[index].Selected = true;
            if (_beforeSelectedPage.PageVisible)
                ObjectsGroupTabControl.SelectedTabPage = _beforeSelectedPage;
            SetRibbonViewKind(index);
        }

        /// <summary>
        /// Помечает в риббоне тип объектов как выбранный
        /// </summary>
        /// <param name="index"></param>
        private void SetRibbonViewKind(int index)
        {
            var typeItem = ViewTypesButtonsList.ButtonsCollection[index];
            foreach (RibbonItem item in ViewTypesButtonsList.ButtonsCollection)
            {
                item.SetState(
                    item == typeItem ?
                    (item.State | RibbonItemChangedStates.Checked) & ~RibbonItemChangedStates.Selected :
                    item.State & ~RibbonItemChangedStates.Checked & ~RibbonItemChangedStates.Selected);
            }                        
            ViewTypesButtonsList.EnsureVisible(typeItem);
            typeItem = ViewTypesButtonsList.DropDownItems[index];
            foreach (RibbonItem item in ViewTypesButtonsList.DropDownItems)
            {
                item.SetState(
                    item == typeItem ?
                    (item.State | RibbonItemChangedStates.Checked) & ~RibbonItemChangedStates.Selected :
                    item.State & ~RibbonItemChangedStates.Checked & ~RibbonItemChangedStates.Selected);
            }            
        }

        private void ViewIndicatorsButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewSituationsButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewTablesButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewDimensionsButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewCubesButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewTimeseriesButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewModelsButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewCalculationsButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewClassificationProblemsButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }   

        private void ViewActionsetsButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewShortcutsButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewAllObjectsButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewIndicatorsDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }   

        private void ViewSituationsDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewTablesDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewDimensionsDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewCubesDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewTimeseriesDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewModelsDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewCalculationsDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewClassificationProblemsDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }   

        private void ViewActionsetsDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewShortcutsDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ViewAllObjectsDropButton_Click(object sender, EventArgs e)
        {
            ObjectKindRibbonClick(sender);
        }

        private void ShortInfoButton_Click(object sender, EventArgs e)
        {
            SetView(ViewType.Short);
        }

        private void FullInfoButton_Click(object sender, EventArgs e)
        {
            SetView(ViewType.Full);
        }

        private void SelectAllButton_Click(object sender, EventArgs e)
        {
            SelectAllObjects();
        }

        private void BackNavigationButton_Click(object sender, EventArgs e)
        {
            HistoryGo(Directions1D.Back);
        }

        private void ForwardNavigationButton_Click(object sender, EventArgs e)
        {
            HistoryGo(Directions1D.Forward);
        }

        private void HistoryForwardButton_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //теперь риббоныHistoryGo(e.ClickedItem.Owner.Items.IndexOf(e.ClickedItem), Directions1D.Forward);
        }

        private void HistoryBackButton_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //теперь риббоныHistoryGo(e.ClickedItem.Owner.Items.IndexOf(e.ClickedItem), Directions1D.Back);
        }

        /// <summary>
        /// Обрабатывает клик по пункту истории навигации
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void historyItem_Click(object sender, EventArgs e)
        {
            var me = sender as RibbonButton;
            var owner = me.CanvasControl as RibbonDropDown;
            bool back = owner.ParentItem == BackNavigationButton;
            var dropdownItems = owner.Items as RibbonItemsCollection;
            HistoryGo(dropdownItems.IndexOf(me), back ? Directions1D.Back : Directions1D.Forward);
        }

        /// <summary>
        /// Заполняет меню перемещения по истории
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="direction"></param>
        private void FillHistoryMenu(RibbonItemsCollection collection, Directions1D direction)
        {
            collection.Clear();
            Func<int, int> incrementer = x => direction == Directions1D.Back ? x - 1 : x + 1;
            for (int i = incrementer(_historyFocus); (i >= 0) && (i < _objectsHistory.Count); i = incrementer(i))
            {
                MetadataObjectsHistoryPoint histItem = _objectsHistory[i];
                var historyMenuItem = new RibbonButton(histItem.Descriptor.ToString());
                historyMenuItem.SmallImage = histItem.Descriptor.GetImage(MetadataObjectImageSize.Small, MetadataObjectState.Normal);
                historyMenuItem.Click += new EventHandler(historyItem_Click);
                collection.Add(historyMenuItem);
                //ToolStripItem historyItem = collection.Add(_objectsHistory[i].ToString());
            }
        }

        private void HistoryBackButton_DropDownOpening(object sender, EventArgs e)
        {
            //теперь риббоныFillHistoryMenu(HistoryBackButton.DropDownItems, Directions1D.Back);
        }

        private void HistoryForwardButton_DropDownOpening(object sender, EventArgs e)
        {
            //теперь риббоныFillHistoryMenu(HistoryForwardButton.DropDownItems, Directions1D.Forward);
        }

        private void BackNavigationButton_DropDownShowing(object sender, EventArgs e)
        {
            FillHistoryMenu(BackNavigationButton.DropDownItems, Directions1D.Back);
        }

        private void ForwardNavigationButton_DropDownShowing(object sender, EventArgs e)
        {
            FillHistoryMenu(ForwardNavigationButton.DropDownItems, Directions1D.Forward);
        }

        private void UpFolderButton_Click(object sender, EventArgs e)
        {
            FolderUp();
        }

        private void RefreshAllButton_Click(object sender, EventArgs e)
        {
            RefreshAll();
        }

        private void OpenObjectButton_Click(object sender, EventArgs e)
        {
            OpenSelectedObject();
        }

        private void GotoObjectButton_Click(object sender, EventArgs e)
        {
            GoToShortcutAim();
        }

        private void RenameButton_Click(object sender, EventArgs e)
        {
            StartObjectRenaming();
        }

        private void ImportTab_ButtonMoreClick(object sender, EventArgs e)
        {
            ShowDataExtractionDialog();
        }

        private void ImportButton_Click(object sender, EventArgs e)
        {
            ShowDataExtractionDialog();
        }

        private void ImportToObjectButton_Click(object sender, EventArgs e)
        {
            ShowDataExtractionDialog(true);
        }

        private void SearchButton_Click(object sender, EventArgs e)
        {
            ShowFindObjectDialog();
        }

        /*/// <summary>
        /// Отображает диалог создания модели из риббона
        /// </summary>
        /// <param name="kind"></param>
        private void ShowRibbonCreateObjectDialog(ModelKind kind)
        {
            ShowRibbonCreateObjectDialog(MetadataObjectKind.Model, (int)kind);
        }

        /// <summary>
        /// Отображает диалог создания измерения из риббона
        /// </summary>
        /// <param name="kind"></param>
        private void ShowRibbonCreateObjectDialog(DimensionKind kind)
        {
            ShowRibbonCreateObjectDialog(MetadataObjectKind.Dimension, (int)kind);            
        }

        /// <summary>
        /// Отображает диалог создания объекта из риббона
        /// </summary>
        /// <param name="kind"></param>
        private void ShowRibbonCreateObjectDialog(MetadataObjectKind kind)
        {
            ShowRibbonCreateObjectDialog(kind, -1);
        }*/

        /*/// <summary>
        /// Отображает диалог создания объекта из риббона
        /// </summary>
        /// <param name="kind"></param>
        private void ShowRibbonCreateObjectDialog(MetadataObjectKind kind, int subKind)
        {
                 
            ShowCreateObjectDialog(kind, subKind);
        }*/

        private void CreatingObjectsTreePanel_ButtonMoreClick(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Folder);
        }

        private void CreateFolderButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Folder);
        }


        private void CreateIndicatorButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Indicator);
        }

        private void CreateIndicatorCategorialStringButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Indicator, (int)IndicatorType.CategorialString);
        }

        private void CreateIndicatorOrderedStringButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Indicator, (int)IndicatorType.OrderedString);
        }

        private void CreateIndicatorIntegerButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Indicator, (int)IndicatorType.Integer);
        }

        private void CreateIndicatorFloatButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Indicator, (int)IndicatorType.Float);
        }

        private void CreateIndicatorDateTimeButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Indicator, (int)IndicatorType.DateTime);
        }

        private void CreateTableButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Table);
        }

        private void CreateDimensionButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Dimension);
        }

        private void CreateCubeButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Cube);
        }

        private void CreateFactsDimensionButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(DimensionKind.Facts);
        }

        private void CreateCalendarDimensionButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(DimensionKind.Calendar);
        }

        private void CreateTimeseriesButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.TimeSeries);
        }

        private void CreateModelButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Model);            
        }

        private void CreateCalculationButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Calculation);
        }

        private void CreateClassificationProblemButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.ClassificationProblem);
        }

        private void CreateClassificationProblemWithTrainingButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.ClassificationProblem, (int)ClassificationProblemKind.WithTraining);
        }

        private void CreateClassificationProblemOnHierarchy_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.ClassificationProblem, (int)ClassificationProblemKind.OnHierarchy);
        }   

        private void CreateActionsetButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.ActionSet);
        }

        private void CreateShortcutButton_Click(object sender, EventArgs e)
        {
            ShowCreateObjectDialog(MetadataObjectKind.Shortcut);
        }

        /// <summary>
        /// Обрабатывает клик по пункту меню моделей
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void modelItem_Click(object sender, EventArgs e)
        {
            var me = sender as RibbonButton;
            var owner = me.CanvasControl as RibbonDropDown;            
            var dropdownItems = owner.Items as RibbonItemsCollection;
            ShowCreateObjectDialog((ModelType)(dropdownItems.IndexOf(me) + 1));
        }

        /// <summary>
        /// Заполняет меню создания моделей
        /// </summary>
        /// <param name="collection"></param>        
        private void FillModelsMenu(RibbonItemsCollection collection)
        {
            collection.Clear();
            for (int i = 1; i < MetadataSharedMethods.ModelsCount + 1; i++)
            {                
                var modelItem = new RibbonButton(MetadataSharedMethods.GetModelKindNameByIndex(i));                
                modelItem.Click += new EventHandler(modelItem_Click);
                collection.Add(modelItem);                
            }
        }

        private void CreateModelButton_DropDownShowing(object sender, EventArgs e)
        {            
            FillModelsMenu(CreateModelButton.DropDownItems);
        }

        private void AttachShortcutButton_Click(object sender, EventArgs e)
        {
            AttachShortcut();
        }

        private void DeleteButton_Click(object sender, EventArgs e)
        {
            DeleteSelectedObjects();
        }

        private void ToggleVisibleObjectsButton_Click(object sender, EventArgs e)
        {
            ToggleObjectsGroups();
        }

        private void TogglePropertiesButton_Click(object sender, EventArgs e)
        {
            ToggleObjectProperties();
            if (ObjectsList.SelectedItems.Count == 1)
                UpdateObjectProperties();
        }

        private void SettingsButton_Click(object sender, EventArgs e)
        {
            ShowSettings();
        }

        private void IDEButton_Click(object sender, EventArgs e)
        {
            ShowIDEWindow();
        }

        private void ObjectsList_BeforeLabelEdit(object sender, LabelEditEventArgs e)
        {            
            _inObjectF2Renaming = true;
            UpdateAvailableActions();
        }

        private void ObjectsTree_BeforeLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            _inObjectF2Renaming = true;
            UpdateAvailableActions();
        }                               
    }
}
